Migrating from groovy to Kotlin based Gradle build scripts in Android
Being android developers we have been using Kotin extensively for last one year so now we do have quite some grasp on the language. Gradle also started building capabilities to write build scripts in kotlin. Gradle traditionally supported groovy, which most of us android developers didn’t understood much. Using Kotlin would change that. So let us dive into using kotlin based gradle build scripts in Android projects.
What will we get?
Make best use of IDE with gradle scripts
- Code completion
- Error detection
- Go to declaration in IDE (command + click on mac)
Example migrating from groovy based scripts to Kotlin
You will have to create .gradle.kts files in the same directories where various .gradle files resides. I have a simple android project at this repo https://github.com/vashisthg/KotlinDslExample/tree/809ade0c8cfc09e0210142f9029370896cd3e737 . I will demonstrate the migration with examples from this repo. The git commits in the repo correspond to the points below.
1. Change settings.gradle to settings.gradle.kts link
2. Change root level build.gradle to build.gradle.kts link
This is also pretty straight forward. One big difference is how a gradle task in created in kotlin
which in groovy looked like this
3. Change app level build.gradle to build.gradle.kts link
Observe how adding plugin is different with kotlin
and how build types are referenced
This is the most exciting part. Gradle compiles the code inside buildSrc and put it in the classpath of your build script. What this means is that you can put complex logic in here, or what I have done in this example is to keep dependencies and version numbers in the kotlin objects here. This way the dependencies could be used in gradle files along with autocompletion support.
So If you put following file in buildSrc
then it could be used in dependencies as
- Droid Kaigi conference app https://github.com/DroidKaigi/conference-app-2018
- Samples in gradle kotlin-dsl github repo https://github.com/gradle/kotlin-dsl/tree/master/samples
Issue: Android Extensions experimental mode not working
First issue experienced after migrating to gradle kotlin dsl was about experimental mode not working. https://github.com/gradle/kotlin-dsl/issues/644
To fix it I used the workaround https://github.com/gradle/kotlin-dsl/issues/644#issuecomment-398502551