Kotlin DSL 入门
传统的 Gradle 使用 Groovy 语言编写,而现代 Android 开发已全面转向 Kotlin DSL (.gradle.kts)。
1. 为什么选择 Kotlin DSL?
- 编译时检查: 拼写错误会在编写时直接提示,而不是等到构建时才报错。
- 出色的 IDE 支持: 更好的代码补全、跳转到定义以及重构功能。
- 语言统一: 开发 App 用 Kotlin,配置脚本也用 Kotlin,减少心智负担。
2. 核心语法对比
kotlin
// 使用双引号,赋值使用 =
plugins {
id("com.android.application")
}
android {
compileSdk = 34
defaultConfig {
applicationId = "com.example.app"
}
}groovy
// 使用单引号,赋值可省略 =
plugins {
id 'com.android.application'
}
android {
compileSdk 34
defaultConfig {
applicationId "com.example.app"
}
}3. 常见属性访问
在 Kotlin DSL 中,某些属性需要通过 by 或 getByName 访问。
kotlin
// 获取名为 "release" 的构建类型
val release = buildTypes.getByName("release")
// 定义自定义属性
val myProperty: String by project