This is small overview how to migrate your groovy buildfiles into Kotlin DSL.
Using the Kotlin DSL for gradle build files improves the editors typing experience in many ways.
First of all, the groovy syntax doesn't support refactoring nor auto-completion while editing in most IDEs.
Build import | Syntax highlighting | Semantic editor | |
---|---|---|---|
IntelliJ IDEA | ✓ | ✓ | ✓ |
Android Studio | ✓ | ✓ | ✓ |
Eclipse IDE | ✓ | ✓ | ✖ |
CLion | ✓ | ✓ | ✖ |
Apache NetBeans | ✓ | ✓ | ✖ |
Visual Studio Code | ✓ | ✓ | ✖ |
Visual Studio | ✓ | ✖ | ✖ |
- Getting started
- settings.gradle
- apply from
- apply plugin
- placeholders
- tasks
- versioning
- Under the hood
- Links
To start with a migration, it is recommended to apply these 4-steps to reduce the warnings and errors.
- single quotes 'string' or double quotes "string"
- make ambiguous statements property by using the assignment operator
- change failing statements into function invocations
- rename the goovy script to *.gradle.kts
settings.gradle
include ':App'
settings.gradle.kts
include(":App")
build.gradle
apply from: "kayleeSettings.gradle"
build.gradle.kts
apply(from = "kayleeSettings.gradle")
build.gradle
apply plugin: "com.android.application"
build.gradle.kts
apply(plugin = "com.android.application")
improved kotlin build.gradle.kts
plugins {
id("com.android.application")
}
build.gradle
manifestPlaceholders = [isFirebaseTrackingDeactivated: false]
build.gradle.kts
manifestPlaceholders = mapOf("isFirebaseTrackingDeactivated" to false)
build.gradle
task clean(type: Delete) {
delete rootProject.buildDir
}
build.gradle.kts
tasks.register("clean", Delete::class) {
delete(rootProject.buildDir)
}
build.gradle
ext {
compileSdkVersion = 29
}
rootProject.ext.compileSdkVersion
There are different approaches for version management
build.gradle.kts
allprojects {
ext {
set("compileSdkVersion", 29)
}
}
build.gradle.kts
buildscript {
extra.apply{
set("compileSdkVersion", 26)
}
}
create a file buildSrc/build.gradle.kts
plugins {
`kotlin-dsl`
}
buildSrc/src/main/kotlin/Constants.kt
object Constants {
const val kotlinVersion = "1.3.70"
}
build.gradle.kts
targetSdkVersion(Constants.targetSdkVersion)
gradel.properties
compileSdkVersion = 29
build.gradle.kts
buildScript {
val kotlinVersion by project
}
You may ask how gradle will find plugins like java
?
build.gradle.kts
plugins {
java
}
It is using inline functions to resolve the dependency
inline val org.gradle.plugin.use.PluginDependenciesSpec.`java`: org.gradle.plugin.use.PluginDependencySpec
get() = id("org.gradle.java")