Power-up your Gradle build files with Kotlin

Tips & recipes for KTS build files

Florian Le Ficher
Feb 19, 2020 · 5 min read
Image for post
Image for post
Kotlin, like a boss. Discover our rabbit.

Kotlin build scripts have clear advantages over Groovy like having auto-completion support and writing custom Gradle tasks becomes easier as it is in the same language as your source code. Kotlin everywhere!

We’re not going to describe how to convert a whole project using Groovy to use Kotlin instead — a lot of articles already describe step-by-step how to do it.

This article will provide you some tips to improve your build files and make the configuration of your projects easier.

Convert your project to use Kotlin script files

To use Kotlin build script files, you first need to create a build.gradle.kts file inside a buildSrc folder into the root of your project:

plugins {
`kotlin-dsl`
}
repositories {
jcenter()
}

Then, try to do a Sync Project with Gradle Files. When it’s done, you can start converting your Gradle build files to use Kotlin by adding .kts extension to your .gradle files. You will have some errors that you need to fix. I advise you to start with small files to understand what you’ll have to change.

Declaring your dependencies

One of the main showcases of using KTS is to declare common dependencies into a single file. This file will include version numbers to ensure that every module uses the same dependencies versions.

You can create a Libraries.kt file into your buildSrc folder:

Libraries.kt

In this sample, we’ve declared an inner class Kotlin with dependencies declaration related to Kotlin. Each dependency uses the same variable. We can do the same for every other dependency we have in our project to ensure having the same version for each library.

Then in our modulesbuild.gradle.kts files, you can use these dependencies quite easily:

app build.gradle.kts

This is it! No more need to use hardcoded strings inside your build.gradle.kts files!

Declaring plugins dependencies

Same as for libraries, we can create constants for our plugins inside a Plugins.kt inside the buildSrc folder:

Plugins.kt

We’re using extensions functions from Kotlin to have a convenient way to use them in our build files:

Plugins declaration in our app build.gradle.kts file

It’s now way cleaner than before and less hardcoded strings.

Improve build config fields declaration

With Gradle, you can declare build configuration fields that can be used in your code. Usually, we declare a build config field this way:

buildConfigField(“String”, “TIME”, “\”${42}\””)

But it’s quite ugly and error-prone because you have to write the field type with a string and add escaped quotes to the value.

Thanks to Kotlin, we can improve this by creating some extension functions:

BuildConfig extensions

Declaring build config fields from ou Gradle files is now way simpler (our functions can be used from a flavor or a build type):

buildConfigBoolean(“ENABLE_CRASH_REPORTING”, true)  buildConfigString(“TIME”, “42”)

You can add extra functions to support all other types.

Hint: Instead of having a different function name for each type (buildConfigString, buildConfigBoolean), etc.) , you can create functions that have the same name buildConfigField but with different value types:

fun BaseFlavor.buildConfigField(name: String, value: Int) =
buildConfigField("Int", name, value.toString())
fun BaseFlavor.buildConfigField(name: String, value: Float) =
buildConfigField("Float", name, value.toString())
// etc

Inject build types properties

Some SDKs require you to have an API key in your Android manifest file, which will have different values depending on your build type (debug key on debug app and a production key on release app).

In this case, you can use manifest placeholders to replace the meta-data value from your manifest depending on the build type (but you can do the same to create BuildConfig fields):

Build types declaration

By using a sealed class we can define our Debug and Release build types and having their definition in one single place. This is quite useful when you have a lot of keys/config fields that will be used across your application modules. You can also do the same for your flavors by using the same logic.

Create custom tasks

You can also create Gradle tasks easily with Kotlin. You need to create your tasks inside your buildSrc folder. The way you create tasks is the same as before by creating a class task that extends DefaultTask or any other subclass.

In our sample, we have a simple custom task that pings an URL and prints a result:

A custom task in Kotlin

In this task, you may see that we use Request class from OkHttp library. You can use external dependencies inside your buildSrcfolder by declaring them inside the dependenciesblock in the buildSrc/build.gradle.kts file (as you will do for any other dependencies in your modules):

dependencies {
//...

implementation("com.squareup.okhttp3:okhttp:4.3.1")
}

Note that you can’t use the constants declared inside the Libraries.kt from this file, so you need to write the full dependency string.

We hope these tips were useful to you or may have inspired you into creating.

Remember that the Android Gradle Plugin doesn’t fully support Kotlin DSL script files for the moment (will be added to Android Studio 4.0). However, you can use it in your production project right now without any problem (we’ve been using the Android Studio 3.5.3 version in our samples and it was working well). Sometimes you may have some errors in your KTS files when upgrading your previous script files or when syncing with Gradle. Cleaning your project files and Gradle caches may solve your problems.

You can have more examples of how KTS can make our lives better on the repository I’ve specially created for this article:

Now take some time to update your whole projects to KTS! 🚀

If you want to join our Bureau of Technology or any other Back Market department, take a look here, we’re hiring! 🦄

Image for post
Image for post
www.backmarket.com

Back Market Engineering

Creative engineers building a less wasteful world …

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store