Kotlin 速查表
变量声明
// 只读变量
val name: String = "Kotlin"
val name2 = "Kotlin" // 类型推断
// 可变变量
var count = 0
var age: Int = 25
// 常量
const val MAX_SIZE = 100
数据类型
// 整数
val int: Int = 42
val long: Long = 42L
val byte: Byte = 42
// 浮点
val double: Double = 3.14
val float: Float = 3.14f
// 字符
val char: Char = 'A'
// 布尔
val bool: Boolean = true
// 字符串
val str: String = "Hello"
val raw = """多行
字符串"""
// 数组
val arr = arrayOf(1, 2, 3)
val intArray = intArrayOf(1, 2, 3)
可空类型
// 可空类型
var name: String? = null
// 安全调用
val len = name?.length
// Elvis 操作符
val length = name?.length ?: 0
// 非空断言
val len2 = name!!.length
// let 使用
name?.let { println(it) }
控制流
// if 表达式
val max = if (a > b) a else b
// when 表达式
val result = when (x) {
1 -> "one"
in 2..10 -> "two to ten"
else -> "other"
}
// for 循环
for (i in 1..10) { }
for (i in 10 downTo 1) { }
for (i in 1..10 step 2) { }
函数
// 基本函数
fun greet(name: String): String = "Hello, $name"
// 默认参数
fun greet(name: String = "World") = "Hello, $name"
// 可变参数
fun sum(vararg nums: Int) = nums.sum()
// Lambda 参数
fun operate(x: Int, op: (Int) -> Int) = op(x)
operate(5) { it * 2 } // 10
类
// 数据类
data class User(val name: String, val age: Int)
// 单例
object Config {
val url = "api.example.com"
}
// 伴生对象
class MyClass {
companion object {
fun create() = MyClass()
}
}
集合操作
val list = listOf(1, 2, 3, 4, 5)
// map
list.map { it * 2 } // [2, 4, 6, 8, 10]
// filter
list.filter { it > 3 } // [4, 5]
// reduce/fold
list.reduce { acc, i -> acc + i } // 15
list.fold(10) { acc, i -> acc + i } // 25
// find
list.find { it > 3 } // 4
// groupBy
listOf("a", "b", "ab").groupBy { it.first() }
// {a=[a, ab], b=[b]}
协程
import kotlinx.coroutines.*
// 启动协程
runBlocking {
launch { /* 异步任务 */ }
// 等待结果
val result = async { fetchData() }.await()
}
// 调度器
Dispatchers.Default // CPU 密集
Dispatchers.IO // IO 操作
Dispatchers.Main // UI 线程
常用函数
// let / run / also / apply
"Hello".let { it.uppercase() }
"Hello".run { uppercase() }
"Hello".also { println(it) }
"Hello".apply { println(length) }
// takeIf / takeUnless
10.takeIf { it > 5 }
10.takeUnless { it > 5 }
// require / check
requireNotNull(input) { "不能为空" }
check(isValid) { "状态无效" }
空安全速查
| 操作 | 语法 | 说明 |
|---|---|---|
| 安全调用 | name?.length | null 返回 null |
| Elvis | name ?: "default" | null 返回默认值 |
| 非空断言 | name!! | null 抛异常 |
| 安全转换 | obj as? String | 失败返回 null |
常见操作符
// in / !in
x in 1..10
x !in list
// is / !is
x is String
x !is Int
// == / ===
a == b // 值相等
a === b // 引用相等
常用库导入
import kotlin.math.* // 数学函数
import kotlin.random.* // 随机数
import kotlin.text.* // 字符串处理
import kotlinx.coroutines.* // 协程
import kotlinx.coroutines.flow.* // Flow