The Kotlin DSL

Gradle takes a build script in two languages. The Groovy DSL is the older one and the one most examples on the internet use; the Kotlin DSL is the one Gradle recommends for a new build, because an IDE completes it from the types and a mistake is a compile error before a task runs. The same build is written twice below, and both of them run.

The same build in Kotlin

The file names change with the language: settings.gradle.kts and build.gradle.kts. Two projects cannot keep both kinds in one folder: Gradle picks the .kts file when both exist.

settings.gradle.kts

rootProject.name = "shop"

build.gradle.kts

plugins { java } group = "com.example" version = "1.0.0" repositories { mavenLocal() } tasks.register("summary") { description = "Prints the coordinates of the project" group = "help" val label = project.group.toString() + ":" + project.name + ":" + project.version doLast { println(label) } }

It runs

Gradle compiles the Kotlin script before it runs the build, which is why the first build of a Kotlin project is slower than the first build of the same project in Groovy. The output is the same, because it is the same task:

gradle -q summary --console=plain --offline --no-daemon

com.example:shop:1.0.0

What differs

Groovy Kotlin
id 'java' java: a function of the plugin scope
group = 'com.example' with a single-quoted string group = "com.example": Kotlin has no single-quoted strings, and the type is Any
def label = "${a}:${b}" val label = a.toString() + ":" + b or a $ template over a non-null value
println label println(label)
a typo appears when the task runs a typo fails to compile before any task runs

The Kotlin DSL is not a different Gradle: the same plugins, the same tasks, the same build/ folder. A build can move from one to the other file by file, and a Gradle build with both is a build with two languages to read.

Why these blocks are plain

The code blocks of this site are coloured by a highlighter per language, and there is no Kotlin highlighter yet: the Kotlin blocks on this page are plain text. The Groovy blocks of the other lessons are coloured. A Kotlin build script is short and its syntax is close to a Groovy one, so the loss is small, and a page that says it is honest about it.

Related

Article author: Arthur Isaev