- Kotlin DSL: Gradle scripts in Android made easy
- Let’s get started
- Is there anything left to do? 🤔
- AppConfig.kt:
- Versions.kt
- AppDependencies.kt
- settings.gradle
- settings.gradle.kts
- build.gradle
- build.gradle.kts
- Styling TextView using Kotlin DSL.
- Output:
- Migrating Gradle Build Scripts to Kotlin DSL
- Migrating Gradle Build Scripts to Kotlin DSL
- Howdy people! It’s bean a while since Gradle released support for Kotlin scripts. We have been writing Gradle…
- Why does Groovy suck?
- Kotlin Script to The Rescue
- Why Kotlin scripts are awesome:
- Migrate to Gradle Kotlin Script
- Gradle support
- Step-1 Convert Settings.gradle File
- Step-2 Convert Project’s build.gradle File
- Step-3 Convert App Level build.gradle File
- The “android< >” Block
- The dependencies < >Block
Kotlin DSL: Gradle scripts in Android made easy
If you are scared of Gradle scripts with unfamiliar groovy syntax files, then Kotlin DSL is made for you. Its time to face the Gradle scripts with more confidence. In this article, we will convert some common Groovy-based Gradle scripts into Kotlin DSL scripts.
Let’s get started
Open half baked side android project 😉 of yours. In your project-level root folder create a folder named buildSrc same as that of your app/ folder in your project. This is a special folder to enable the Gradle scripts at the project level. Hit the sync button and you will see how these changes and adds some temporary files inside it.
Half the battle is done 😀 now in order to enable the Kotlin DSL we gotta do something more here. So put our lazy brain to work and create a file inside buildSrc naming it build.gradle.kts open now the newly created file to add some code that tells Gradle to enable the Kotlin-DSL plugin for our project.
Sync now, That’s it Battle is won, and Kotlin DSL is enabled in our project.
Is there anything left to do? 🤔
Yes, whatever we have done is of no use until we put Kotlin DSL into some action.
Kotlin DSL brings the simplicity of the Kotlin language syntax and rich API set right into the script files on top of that code completion makes it perfect to work with Gradle script files. We will use this to manage our dependencies and project settings configurations more elegantly. Kotlin DSL files have extension as .kts so we will be converting all of our .gradle files to .gradle.kts
Before converting our files to Kotlin DSL let’s have some necessary files in place in order to go ahead. Create folders inside the buildSrc folder as below and create the stated files.
AppConfig.kt:
This file helps us manage our app-level configurations related to the project at once place.
Versions.kt
This file helps us separate our versioning of the libraries in one place.
AppDependencies.kt
This file holds all the dependencies of our app related to UI, test, and other third-party libraries. Apart from that this also holds the Kotlin extension functions for implementation, testImplementation, androidTestImplementation, kapt which basically now accepts a list of String (dependencies) which is helpful for adding multiple dependencies at once instead of adding one by one in build.gradle file. You can play around and separate dependencies based on the module name also by creating a different list of dependencies for your module and add all at once by using a single line of code Gradle script.
Here is how it will look like when we are done adding all the Kotlin files.
Also, it’s no hard and fast rule we can also manage all these constants in one file also but if your project is large enough to make you go mad for a single change then it’s better to have separate the concerns in different files for different purposes. Let’s convert
settings.gradle
Our existing code for settings.gradle file as below
settings.gradle.kts
include is now just a function taking vararg of String to include the modules in the project. Moving next we gonna change our project level build.gradle file
build.gradle
build.gradle.kts
Kotlin DSL version is almost the same since it’s using DSL to map those syntaxes and tries to be as close as possible for example.
classpath is just a regular Kotlin function taking String as input. Which we all know and understand and can relate the syntax. Let’s see how our main app-level build.gradle file changes to build.gradle.kts
Plugins are the first thing in the main app-level Gradle file which enables the android support in regular Intellij project or Kotlin support in an android project or any third party plugin which needed at module level can be applied in this file, we will see show that changes
will be changed to
or you can use another way of adding plugins as shown below, the above one is the DSL way of doing things.
now let’s try to go chunk by chunk for an android block with the basic setup.
will be changed to
Now it’s possible to directly access the Kotlin object constants or any other constants like as shown above. Here we are using the earlier created constants in file AppConfig for the app level configurations. Next, let’s see how we can create the debug and release versions.
will be changed to
you don’t have to create debug because it’s there by default until unless needed to change some properties. If so then do something like this.
coming to the main dependencies this is how it was like before
will be now changed to below
this is quite maintainable, easy to read & understand.
putting all this together will look like as below.
If you have any android module, conversion goes almost the same for the modules as well instead of using an android id plugin use library plugin id.
Kotlin DSL is not limited to the usages across Gradle scripts it’s way broader than just scripting. Let’s go and explore this side of Kotlin DSL by putting this into implementation.
Styling TextView using Kotlin DSL.
Let’s start by creating the backbone which will support the DSL.
in our MainActivity we will use this as follow.
Output:
This is the very basic example of Kotlin DSL, we can write to express almost anything using this. This is a much more clean and expressive way of doing programming. Since it uses Kotlin lambda expressions extensively to achieve this, we should be conscious of the extra classes it generates at the byte code level. So how to fix this 🤔, simply try to inline the lambda expressions where ever possible in order to reduce the extra class which would get generated for the small code blocks.
That’s it folks for today. Please be generous enough to comment for feedback or suggestions or any queries. Thanks for reading 😊.
Источник
Migrating Gradle Build Scripts to
Kotlin DSL
Originally published at:
Migrating Gradle Build Scripts to Kotlin DSL
Howdy people! It’s bean a while since Gradle released support for Kotlin scripts. We have been writing Gradle…
Howdy people! It’s been a while since Gradle released support for Kotlin scripts. We have been writing Gradle script in a language called Groovy since ages. Let’s be honest, We all know that Groovy sucks! Half of the times I have been like this when there’s an issue:
Why does Groovy suck?
- No Auto-Completion🙄
- No Content Assist😞
- No Navigation to Source😕
- Don’t know what to write and how to write😪
- I don’t like it😠
Kotlin Script to The Rescue
Gradle released support for Kotlin scripts and Kotlin DSL(In short, DSL makes the code more readable, it’s built in Kotlin feature). Finally, I don’t have to learn that lame Groovy for Gradle scripts. Now I can write my build scripts in my favorite language Kotlin. When it released, I was like:
I never learned Groovy but now, all I have to do is to be yourself and write Kotlin scripts like a PRO. How cool is that! A single language to manage your whole project. Kotlin script overcomes almost all the cons of Groovy.
Why Kotlin scripts are awesome:
- Auto-Completion😎
- Content Assist😍
- Navigation to Source😱
- Kotlin Extensions support😘
- Errors at compile time instead of runtime💪
- I love it❤️
Writing build scripts in Kotlin is like riding a bike🏍 (Except the bike is on fire🔥).
Sometimes it can be a bit messy to rewrite gradle.build into gradle.build.kts files, especially when all its cache is malfunctioning during that process. Few times I had to reopen my project so that Android Studio can understand properly what is going on. “Refresh all Gradle projects” button has been life saver for me.😉
But don’t worry, Just follow the steps with me and you will be just fine.
Migrate to Gradle Kotlin Script
A nice thing about Kotlin build script is you don’t have to do the extra setup for enabling it. Just rename .gradle file to .gradle.kts file extension and Gradle will consider it as a Kotlin script. Please note that following the steps below in sequence is highly important to avoid intermediate Gradle issues.
Gradle support
To make sure that everything works fine, update your gradle to version 4.10 or higher(5.2.1 is latest at the time of writing this post). To do so, go to your project’s gradle-wrapper.properties and check distributionUrl for the current version. make sure it looks like below:
Step-1 Convert Settings.gradle File
Let’s start with settings.gradle file by renaming (Shift + F6) it to settings.gradle.kts. Now that this file is a Kotlin script, include will behave as a function and “ :app” will be the string argument.
✏️Note that in Groovy, you were able to write single quotes(‘’) in place of double quotes(“”) but in Kotlin , you must have to use double quotes only.
Now that you have converted it in Kotlin, Gradle will identify it accordingly and will process it as Kotlin script. Just sync with Gradle files.
Step-2 Convert Project’s build.gradle File
Rename project level build.gradle to build.gradle.kts. The main difference here is in classpath and in clean task.
classpath is now a function in Kotlin which takes a string argument as shown below:
clean task will no longer be written in Groovy. This is how it looks in Kotlin:
Another thing that can change is that if you have any repositories with url in repositories block. You can change it like this:
That’s it! The file is now completely in Kotlin. If you have some other configurations then you can easily convert it into Kotlin with the help of Auto Completion. If you don’t know how to implement something, you can always navigate to the source code. That’s the beauty of it.
Here is the whole build.gradle.kts file:
You’ll be able to sync your project after completing this step.
Step-3 Convert App Level build.gradle File
Here comes a little bit messy part😵. Open app level build.gradle file and rename it to build.gradle.kts. Don’t try to sync now. It will show lots of errors but don’t worry, we’re going to remove all the errors one by one. Let’s start at the top.
In Groovy, every plugin was being applied individually whereas Kotlin provides plugins<> block to apply all the plugins within a single block.
Here, id() and kotlin() are functions which are used to apply plugins.
id() is used to apply any plugin. All the plugins can be applied using id().
Plugins which are specific to Kotlin can also be applied using kotlin() function. That’s cool😎
Note that when you use kotlin () function, the kotlin prefix will be removed from plugin name and the dash(-) will be replaced by dot(.) . For the sake of simplicity, you can use id () function instead.
The “android< >” Block
Note these points to convert this block in Kotlin:
- compileSdkVersion is a function.
- applicationId is a property.
- minSdkVersion and targetSdkVersion are functions too.
- versionCode and versionName are properties again.
According to the above points, this block will look like this:
buildTypes block is a bit tricky. A function getByName(String) is used to get a build type.
minifyEnabled is a property with name isMinifyEnabled.
proguardFiles and getDefaultProguardFile are functions.
This is how it will look like:
The dependencies < >Block
There should be only one block left (if you don’t have any extra configs hopefully😬) that is the dependencies<> block.
Here, implementation, kapt, api, testImplementation, androidTestImplementation, etc are functions.
The fileTree in implementation() is also a function which takes a map as an argument. Here’s how it will look like:
Here is the whole app level build.gradle.kts file:
Hell Yeah! Sync the project (Hopefully it will compile, let’s have some faith in Gradle). There you go, your project is converted in Kotlin build scripts. Say goodbye to Groovy!
If you’re reading this and you have made it then you’d be probably like this:
or maybe this (I don’t know how you function, it’s an educated guess):
It depends on you.😄 It’s just a matter of time, Gradle will provide kotlin script support by default. That means this all will be directly generated for you. How amazing is that! Till then, Happy coding folks!
Here is the sample project on github you can refer for this tutorial.
Источник