Migrating to build.gradle.kts: in 15 minutes

If you are among those people who has no idea of how to write Gradle in groovy then kotlin DSL is the one for you.
Reason to use kotlin scripts
- Compile time error ❤
- Auto completion
- Source navigation
- Possibility to use extensions
- You have some idea of what you are doing ❤️
- Highly extendable
Why type-safe build logic ?
- Improved Developer experience
- Authoring build logic
- Troubleshooting build related issues
- IDE Support ❤️
- Shorter feedback cycle ❤️
- Less error prone on runtime
Migrate Gradle to kotlin scripts
Migration to kotlin scripts from groovy is very simple and straight forward.
1) replace single quotes with double
2) renaming .gradle to .gradle.kts
3) verify gradle version greater than 5
Step by step Android groovy to kotlin DSL
The 3 files written in groovy will be migrated to kotlin DSL
1) settings.gradle
- Rename file ‘settings.gradle’ to ‘setting.gradle.kts’
- Replace single quotes to double quotes

TO

Sync project and make sure it builds successfully. Do not move to next step without fixing the setting.gradle file
2) Project’s build.gradle
- Rename build.gradle to build.gradle.kts
- Replace single quotes to double quotes
- The class path is a function now which has String parameters.
Dependencies

TO

Clean Task
The clean task will be little different in Kotlin script

TO

Repositories

TO

Sync project and make it build successfully.
3) App’s build.gradle
This is the tricky part among the 3 major steps. This file has to be dealt with one step at a time. In Groovy, every plugin was applied individually but in Kotlin, plugins{} block applies all the plugins within a single block.
So, before we could start we get back to our golden steps.
- Rename build.gradle to build.gradle.kts
- Replace single quotes to double quotes
- Follow the below steps, one block at a time
Plugins

TO

In Kotlin scripts id() and kotlin() functions are used to apply plugins.
id() is used for all plugins.
kotlin() is used for kotlin specific functions. You can also omit the ‘kotlin-’ prefix. dash(-) will be replaced by dot(.)

Android

TO

Build Types
This is perhaps the block which is not simple as the others.

TO

The other functions be pretty easy to figure out.
Product Flavors

TO

Dependencies
The functions implementation, testImplementation, androidTestImplementation, debugImplementation etc. are pretty simple to figure out, following the kotlin function pattern.

TO

Sync and feel amazed
Note: There seem to be some changes on Kotlin 1.4. Stay in touch for updated blog