Kotlin 常用命令速查表

把 Kotlin 日常开发最常用的命令和语法整理成速查,写代码时对照查。

编程语言·共 31 条命令·最后更新 2026-07-19
返回 编程语言

编译与运行 5

kotlinc main.kt -include-runtime -d main.jar
编译为可执行 jar
java -jar main.jar
运行编译后的 jar
kotlinc -script script.kts
运行 Kotlin 脚本
kotlinc-jvm
进入 REPL
kotlin main.kt
直接运行(无需编译)

Gradle 构建 5

./gradlew build
构建项目
./gradlew run
运行主类
./gradlew test
运行测试
./gradlew clean
清理构建目录
./gradlew dependencies
查看依赖

空安全 5

var name: String? = null
可空类型声明
name?.length
安全调用(null 返回 null)
name ?: "default"
Elvis 操作符(null 时给默认值)
name!!.length
非空断言(null 抛异常)
val len = name?.length ?: 0
组合使用

集合操作 10

list.filter { it > 5 }
过滤
list.map { it * 2 }
映射
list.flatMap { it.split(",") }
扁平化映射
list.groupBy { it.category }
分组
list.sortedBy { it.age }
排序
list.distinct()
去重
list.take(5)
取前 5 个
list.drop(3)
丢弃前 3 个
list.firstOrNull { it.id == 1 }
查找第一个匹配
list.partition { it > 0 }
按条件分成两份

协程 Coroutine 6

runBlocking { ... }
阻塞式协程(测试用)
launch { ... }
启动协程(不返回值)
async { ... }
启动协程(返回 Deferred)
delay(1000)
非阻塞延迟
withContext(Dispatchers.IO) { ... }
切换上下文
coroutineScope { ... }
创建协程作用域

💡 提示

  • Kotlin 的空安全是编译期检查,!! 能不用就不用。
  • 协程的 launch 和 async 区别:launch 返回 Job,async 返回 Deferred(可 await)。
  • 集合操作链式调用很优雅,但大数据量时注意中间集合的内存开销。