跳到主要内容

Kotlin 速查表

本文档提供 Kotlin 常用语法和 API 的快速参考,涵盖从基础到高级的各种用法。

变量声明

// 只读变量(val - value)
val name: String = "Kotlin"
val inferred = "类型推断" // 编译器推断类型

// 可变变量(var - variable)
var count = 0
var age: Int = 25

// 延迟初始化
lateinit var service: DataService // 用于 var,稍后初始化

// 惰性初始化
val heavyObject: HeavyObject by lazy {
HeavyObject.create() // 首次访问时初始化
}

// 常量(编译时)
const val MAX_SIZE = 100
const val APP_NAME = "MyApp"

数据类型

基本类型

// 整数类型
val byte: Byte = 127 // 8位
val short: Short = 32767 // 16位
val int: Int = 2147483647 // 32位
val long: Long = 9223372036854775807L // 64位,L后缀

// 浮点类型
val float: Float = 3.14F // 32位,F后缀
val double: Double = 3.1415926535 // 64位(默认)

// 字符与布尔
val char: Char = 'A'
val boolean: Boolean = true

// 数字字面量增强
val oneMillion = 1_000_000
val hex = 0xFF
val binary = 0b00001011

字符串

val str: String = "Hello"

// 字符串模板
val name = "Kotlin"
val greeting = "Hello, $name!"
val expr = "Sum: ${1 + 2}"

// 多行字符串
val text = """
|第一行
|第二行
""".trimMargin()

// 原始字符串(保留格式)
val json = """
{
"name": "Kotlin",
"version": 2.0
}
"""

// 多美元插值(Kotlin 2.1 预览)
val schema = $$"""{"$schema": "..."}"""

数组

val intArray = intArrayOf(1, 2, 3)
val strArray = arrayOf("a", "b", "c")

// 创建指定大小
val zeros = IntArray(10) // 全0
val squares = Array(5) { i -> i * i } // [0, 1, 4, 9, 16]

// 访问和修改
val first = intArray[0]
intArray[0] = 10

可空类型

// 可空类型声明
var name: String? = null

// 安全调用 ?.
val length = name?.length // null 如果 name 为 null

// Elvis 操作符 ?:
val len = name?.length ?: 0 // 提供默认值

// 非空断言 !!(慎用)
val forceLen = name!!.length // null 时抛 NPE

// 安全转换 as?
val num = str as? Int // 转换失败返回 null

// let 处理可空值
name?.let {
println("Name: $it")
}

// takeIf / takeUnless
val valid = input.takeIf { it.isNotEmpty() }
val invalid = input.takeUnless { it.isBlank() }

控制流

条件表达式

// if 表达式
val max = if (a > b) a else b

// 多分支 if
val result = if (score >= 90) "A"
else if (score >= 80) "B"
else "C"

// when 表达式
val desc = when (x) {
1 -> "one"
2, 3 -> "two or three"
in 4..10 -> "four to ten"
!in 1..100 -> "out of range"
is Int -> "is Int"
else -> "other"
}

// when 守卫条件(Kotlin 2.1 预览)
when (animal) {
is Cat if animal.isHungry -> feed()
is Dog -> play()
else -> ignore()
}

// 无参数 when
val grade = when {
score >= 90 -> "A"
score >= 80 -> "B"
else -> "F"
}

循环

// for 循环
for (i in 1..10) { } // 1到10
for (i in 1 until 10) { } // 1到9
for (i in 10 downTo 1) { } // 10到1
for (i in 1..10 step 2) { } // 1,3,5,7,9

// 遍历集合
for (item in list) { }
for ((index, item) in list.withIndex()) { }

// 遍历 Map
for ((key, value) in map) { }

// while 循环
while (condition) { }
do { } while (condition)

// 循环控制
break // 跳出循环
continue // 跳过本次
break@label // 跳出标签循环

函数

函数定义

// 标准函数
fun add(a: Int, b: Int): Int {
return a + b
}

// 单表达式函数
fun double(x: Int) = x * 2

// 默认参数
fun greet(name: String, greeting: String = "Hello") = "$greeting, $name!"

// 命名参数
greet(name = "Tom", greeting = "Hi")

// 可变参数
fun sum(vararg nums: Int) = nums.sum()
sum(1, 2, 3, 4, 5)
sum(*intArrayOf(1, 2, 3)) // 展开数组

// 中缀函数
infix fun Int.times(str: String) = str.repeat(this)
2 times "x" // "xx"

// 扩展函数
fun String.isEmail() = contains("@")
"[email protected]".isEmail()

高阶函数与 Lambda

// Lambda 表达式
val add: (Int, Int) -> Int = { a, b -> a + b }

// 尾随 Lambda
list.filter { it > 0 }

// it 隐式参数
list.map { it * 2 }

// 函数引用
list.filter(::isPositive)

// 高阶函数
fun <T> List<T>.customFold(init: T, op: (T, T) -> T): T {
var result = init
for (item in this) result = op(result, item)
return result
}

内联函数

// 内联消除开销
inline fun <T> measure(block: () -> T): T {
val start = System.currentTimeMillis()
return block().also {
println("Time: ${System.currentTimeMillis() - start}ms")
}
}

// reified 类型参数
inline fun <reified T> Any.isInstanceOf(): Boolean = this is T

// noinline:阻止内联
inline fun example(inlined: () -> Unit, noinline stored: () -> Unit)

// crossinline:禁止非局部返回
inline fun runLater(crossinline action: () -> Unit)

类与对象

类定义

// 基本类
class Person(val name: String, var age: Int) {
fun greet() = "Hello, I'm $name"
}

// 数据类(自动生成 equals/hashCode/toString/copy)
data class User(val id: Int, val name: String, val email: String)

// 解构声明
val (id, name, _) = User(1, "Tom", "[email protected]")

// 密封类(受限继承)
sealed class Result {
data class Success(val data: String) : Result()
data class Error(val message: String) : Result()
}

// 枚举类
enum class Status { ACTIVE, INACTIVE, PENDING }
enum class Color(val rgb: Int) {
RED(0xFF0000),
GREEN(0x00FF00)
}

继承与接口

// 抽象类
abstract class Animal(val name: String) {
abstract fun speak()
}

// 继承
class Dog(name: String) : Animal(name) {
override fun speak() = "$name says Woof!"
}

// 接口
interface Flyable {
fun fly()
}

// 实现多个接口
class Bird : Animal("Bird"), Flyable {
override fun speak() = "Chirp"
override fun fly() = "Flying"
}

对象与伴生对象

// 单例对象
object Database {
val url = "jdbc:mysql://localhost/db"
fun connect() { }
}

// 伴生对象(类似静态成员)
class Factory {
companion object {
fun create() = Factory()
}
}
Factory.create()

// 对象表达式(匿名内部类)
val listener = object : OnClickListener {
override fun onClick() { }
}

集合操作

创建集合

// 只读集合
val list = listOf(1, 2, 3)
val set = setOf("a", "b", "c")
val map = mapOf("k1" to "v1", "k2" to "v2")

// 可变集合
val mutableList = mutableListOf(1, 2, 3)
val mutableSet = mutableSetOf(1, 2, 3)
val mutableMap = mutableMapOf("k" to "v")

// 构建
val list = List(5) { it * 2 } // [0, 2, 4, 6, 8]

常用操作

val nums = listOf(1, 2, 3, 4, 5)

// 变换
nums.map { it * 2 } // [2, 4, 6, 8, 10]
nums.filter { it > 2 } // [3, 4, 5]
nums.flatMap { listOf(it, it * 10) } // [1,10,2,20,3,30,4,40,5,50]

// 聚合
nums.sum() // 15
nums.average() // 3.0
nums.reduce { a, b -> a + b } // 15
nums.fold(10) { a, b -> a + b } // 25

// 查找
nums.find { it > 3 } // 4
nums.any { it > 3 } // true
nums.all { it > 0 } // true
nums.count { it > 2 } // 3

// 排序
nums.sorted() // [1, 2, 3, 4, 5]
nums.sortedDescending() // [5, 4, 3, 2, 1]
nums.sortedBy { -it } // [5, 4, 3, 2, 1]

// 分组
nums.groupBy { it % 2 } // {1=[1,3,5], 0=[2,4]}

// 分区
val (even, odd) = nums.partition { it % 2 == 0 }

// 取值
nums.take(3) // [1, 2, 3]
nums.drop(2) // [3, 4, 5]
nums.first() // 1
nums.last() // 5

协程

基本使用

import kotlinx.coroutines.*

// 启动协程
fun main() = runBlocking {
launch {
delay(1000)
println("World!")
}
println("Hello,")
}

// async 返回结果
val deferred = async { expensiveOperation() }
val result = deferred.await()

// 并发执行
coroutineScope {
val one = async { fetchOne() }
val two = async { fetchTwo() }
combine(one.await(), two.await())
}

调度器

// 切换上下文
withContext(Dispatchers.IO) {
// IO 操作
}

withContext(Dispatchers.Default) {
// CPU 密集计算
}

// 常用调度器
Dispatchers.Default // CPU 密集
Dispatchers.IO // 网络/文件 IO
Dispatchers.Main // UI 线程

Flow

import kotlinx.coroutines.flow.*

// 创建 Flow
fun numbers(): Flow<Int> = flow {
for (i in 1..10) {
emit(i)
}
}

// 收集
numbers()
.map { it * 2 }
.filter { it > 5 }
.collect { println(it) }

// 冷流:只有 collect 时才执行
// 缓冲
flow { /*...*/ }
.buffer()
.collect { /*...*/ }

作用域函数

// let:返回结果,参数为 it
"hello".let { it.uppercase() }

// run:返回结果,使用 this
"hello".run { uppercase() }

// with:返回结果,使用 this
with(person) { "$name, $age" }

// apply:返回对象本身,使用 this
StringBuilder().apply {
append("Hello")
append(" World")
}

// also:返回对象本身,参数为 it
listOf(1, 2, 3)
.also { println("Processing: $it") }
.map { it * 2 }
函数对象引用返回值典型场景
letit结果空安全、转换
runthis结果计算
withthis结果多次操作
applythis对象配置
alsoit对象日志、链式

委托

// lazy:延迟初始化
val heavy: Heavy by lazy { Heavy.create() }

// observable:属性变化监听
var name: String by Delegates.observable("") { _, old, new ->
println("$old -> $new")
}

// vetoable:条件性修改
var age: Int by Delegates.vetoable(0) { _, _, new ->
new >= 0 // 只允许非负值
}

// Map 委托
class User(map: Map<String, Any?>) {
val name: String by map
val age: Int by map
}

操作符重载

data class Point(val x: Int, val y: Int) {
operator fun plus(other: Point) = Point(x + other.x, y + other.y)
operator fun minus(other: Point) = Point(x - other.x, y - other.y)
operator fun times(scalar: Int) = Point(x * scalar, y * scalar)

// 索引访问
operator fun get(i: Int) = when(i) {
0 -> x
1 -> y
else -> throw IndexOutOfBoundsException()
}

// 范围
operator fun rangeTo(other: Point) = PointRange(this, other)
}

val p1 = Point(1, 2)
val p2 = Point(3, 4)
val sum = p1 + p2 // Point(4, 6)
val scaled = p1 * 2 // Point(2, 4)
操作符函数示例
+plusa + b
-minusa - b
*timesa * b
/diva / b
%rema % b
++inca++
--deca--
[]get/seta[i]
incontainsa in b
..rangeToa..b
()invokea()

常用工具函数

字符串

str.length           // 长度
str.isEmpty() // 是否为空
str.isBlank() // 是否为空白
str.uppercase() // 大写
str.lowercase() // 小写
str.trim() // 去空白
str.split(",") // 分割
str.replace("a", "b") // 替换
str.substring(0, 3) // 子串
str.startsWith("H") // 前缀
str.endsWith("o") // 后缀
str.contains("ell") // 包含
str.toIntOrNull() // 转整数

集合工具

// 检查
list.isEmpty()
list.isNotEmpty()
list.contains(element)
list.containsAll(other)

// 转换
list.toSet() // 转 Set
list.toMutableList() // 转可变列表
list.toArray() // 转数组
list.joinToString(",") // 转字符串

// 聚合
list.sum()
list.average()
list.maxOrNull()
list.minOrNull()
list.count()

// 复制
list.copyOf()
list.copyOfRange(0, 3)

数学函数

import kotlin.math.*

abs(-5) // 绝对值:5
max(1, 2) // 最大值:2
min(1, 2) // 最小值:1
sqrt(16.0) // 平方根:4.0
pow(2.0, 3.0) // 幂:8.0
round(3.5) // 四舍五入:4.0
floor(3.7) // 向下取整:3.0
ceil(3.2) // 向上取整:4.0
sin(PI / 2) // 正弦:1.0
cos(0.0) // 余弦:1.0
random() // [0,1) 随机数

随机数

import kotlin.random.Random

Random.nextInt() // 随机 Int
Random.nextInt(0, 100) // [0, 100) 随机数
Random.nextDouble() // 随机 Double
Random.nextBoolean() // 随机布尔

// 范围随机
(1..100).random()

异常处理

try-catch-finally

// 基本 try-catch
try {
riskyOperation()
} catch (e: IOException) {
handleError(e)
} finally {
cleanup()
}

// try 作为表达式
val result = try {
parse(input)
} catch (e: ParseException) {
null
}

// 多个 catch 块
try {
// ...
} catch (e: NumberFormatException) {
// 处理数字格式错误
} catch (e: ArithmeticException) {
// 处理算术错误
} catch (e: Exception) {
// 处理其他异常
}

throw 与 Nothing

// 抛出异常
throw IllegalArgumentException("Invalid argument")

// Nothing 类型
fun fail(message: String): Nothing {
throw IllegalStateException(message)
}

// TODO() 函数
fun notImplemented(): String = TODO("等待实现")

预条件函数

// require:参数检查,抛出 IllegalArgumentException
require(age >= 0) { "Age must be non-negative" }
requireNotNull(name) { "Name cannot be null" }

// check:状态检查,抛出 IllegalStateException
check(isInitialized) { "Not initialized" }
checkNotNull(value) { "Value is null" }

// error:表示不应该发生的情况
fun process(role: Role) = when (role) {
Role.ADMIN -> "管理员"
Role.USER -> "用户"
// error("未知角色: $role") // 编译器知道这里不会返回
}

自定义异常

// 简单自定义异常
class ValidationException(message: String) : Exception(message)

// 带参数的自定义异常
class InsufficientFundsException(
val required: Double,
val available: Double
) : IllegalStateException("资金不足:需要 $required,可用 $available")

// 异常层次结构
sealed class AppException(message: String) : Exception(message) {
class UserNotFound(val userId: Long) : AppException("用户不存在: $userId")
class NetworkError(val code: Int) : AppException("网络错误: $code")
}

常见异常类型

异常类型触发场景
NullPointerException访问 null 引用
IllegalArgumentException非法参数
IllegalStateException非法状态
IndexOutOfBoundsException索引越界
NumberFormatException数字格式错误
ArithmeticException算术错误(如除零)
NoSuchElementException元素不存在

注解

声明注解

// 简单注解
annotation class Review

// 带参数的注解
annotation class Author(val name: String)

// 使用
@Author("张三")
class MyClass

元注解

@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@Repeatable
annotation class Api(
val version: String,
val deprecated: Boolean = false
)

@Target 目标类型

类型说明
CLASS类、接口、对象
FUNCTION函数
PROPERTY属性
FIELD字段
CONSTRUCTOR构造函数
VALUE_PARAMETER函数参数
EXPRESSION表达式
FILE文件

@Retention 保留策略

策略源码字节码运行时
SOURCE
BINARY
RUNTIME

使用目标

class Example(
@field:Ann val foo, // 注解字段
@get:Ann val bar, // 注解 getter
@param:Ann val quux // 注解构造参数
)

@file:JvmName("Utils") // 文件级注解
package com.example

内置注解

// @Deprecated
@Deprecated("使用 newMethod()", ReplaceWith("newMethod()"))
fun oldMethod() { }

// @Suppress
@Suppress("UNCHECKED_CAST", "UNUSED_PARAMETER")
fun example() { }

// @JvmStatic - 伴生对象静态方法
companion object {
@JvmStatic
fun staticMethod() { }
}

// @JvmField - 暴露为公共字段
@JvmField
val VERSION = "1.0"

// @JvmOverloads - 生成重载
@JvmOverloads
fun createUser(name: String, age: Int = 0) { }

// @Throws - 声明异常(Java 互操作)
@Throws(IOException::class)
fun readFile(path: String): String { }

// @Volatile - 易变属性
@Volatile
var running = true

// @Synchronized - 同步方法
@Synchronized
fun increment() { }

反射读取注解

// 获取类上的注解
val annotation = MyClass::class.findAnnotation<Author>()

// 获取所有带某注解的方法
MyClass::class.memberFunctions
.filter { it.findAnnotation<Api>() != null }
.forEach { /* ... */ }

常用导入

import kotlin.math.*           // 数学函数
import kotlin.random.* // 随机数
import kotlin.collections.* // 集合扩展
import kotlin.text.* // 文本处理
import kotlinx.coroutines.* // 协程
import kotlinx.coroutines.flow.* // Flow
import kotlin.system.* // 系统相关

Kotlin 版本新特性

Kotlin 2.0

  • K2 编译器:全新架构,编译速度大幅提升
  • 智能类型转换增强:更多场景支持自动类型转换
  • 统一编译架构:JVM、JS、Native 共享架构

Kotlin 2.1(预览)

// Guard 条件(when 守卫)
when (value) {
is String if value.length > 5 -> "Long string"
is String -> "Short string"
else -> "Not a string"
}

// 多美元插值
val json = $$"""{"$schema": "..."}"""

// 非局部 break/continue
list.forEach {
if (it == target) return@forEach
process(it)
}

// @SubclassOptInRequired
@SubclassOptInRequired(ExperimentalApi::class)
interface ExperimentalInterface

快速参考表

空安全操作符

操作语法说明
安全调用obj?.method()null 返回 null
Elvisvalue ?: defaultnull 返回默认值
非空断言value!!null 抛异常
安全转换obj as? Type失败返回 null

相等性

操作语法说明
值相等a == b调用 equals()
引用相等a === b同一对象
类型检查a is T类型判断

范围操作

操作语法说明
闭区间1..10包含10
半开区间1 until 10不包含10
降序10 downTo 1递减
步长1..10 step 2步长为2
检查x in 1..10是否在范围内

参考资料