TExcelTAD
Home › Java Builds: Maven & Gradle › Build Scripts in the Kotlin DSL

Build Scripts in the Kotlin DSL

build.gradle.kts is a Kotlin script. Gradle compiles it (and caches the result) and runs it against a Project object during the configuration phase. Everything you write is ordinary Kotlin: calls with trailing lambdas, properties, vals, loops, functions. The "DSL" part is just a set of well-named APIs and generated accessors that make a build script read like configuration. Gradle also supports the older Groovy DSL (build.gradle); new builds should use Kotlin, which gives IDE completion and compile-time errors.

If Kotlin is new to you, its lambdas and extension functions are the two features build scripts lean on.

Reading a build script as Kotlin

kotlin
plugins {                         // a call: plugins(block) — evaluated first, before the rest
    java                          // a generated accessor for the core plugin id "java"
    id("org.example.tool") version "1.2"   // a community plugin by id and version
}

group = "com.example"             // a property of Project
version = "1.0.0"

repositories {                    // repositories(block), with this = RepositoryHandler
    mavenCentral()
}

dependencies {                    // "implementation" is generated for the configuration of that name
    implementation("org.apache.commons:commons-lang3:3.21.0")
}

java {                            // the extension the java plugin adds, type JavaPluginExtension
    toolchain { languageVersion = JavaLanguageVersion.of(21) }
}

tasks.test {                      // type-safe accessor for the task "test" (type Test)
    useJUnitPlatform()
}

The type-safe accessors (java { }, tasks.test, implementation(...)) only exist for things contributed by plugins applied in the plugins {} block, because Gradle generates them from that block before compiling the rest of the script. Without accessors you use the string-based APIs, which work everywhere (for example in convention plugins):

kotlin
configure<JavaPluginExtension> { toolchain { languageVersion = JavaLanguageVersion.of(21) } }
tasks.named<Test>("test") { useJUnitPlatform() }
"implementation"("org.apache.commons:commons-lang3:3.21.0")

Code, properties and the command line

Because the script is code, you can compute things. Values that should come from outside go into gradle.properties (committed defaults) and can be overridden with -P on the command line, or come from environment variables; read them through providers:

bash · try it yourself
mkdir dsl && cd dsl
cat > settings.gradle.kts <<'KTS'
rootProject.name = "dsl"
KTS
cat > gradle.properties <<'PROPS'
greeting=hello
regions=eu,us
PROPS
cat > build.gradle.kts <<'KTS'
val greeting = providers.gradleProperty("greeting")
val projectName = project.name
val regions = providers.gradleProperty("regions").map { it.split(",") }

fun bannerFor(region: String) = "[$region]".uppercase()

for (region in regions.get()) {
    tasks.register("deploy${region.replaceFirstChar { it.uppercase() }}") {
        group = "deployment"
        val text = greeting.map { "${bannerFor(region)} $it from $projectName" }
        doLast { println(text.get()) }
    }
}
KTS
gradle -q tasks --group deployment | grep deploy
gradle -q deployEu deployUs
gradle -q deployEu -Pgreeting=bonjour
gradle -q deployAsia 2>&1 | sed -n '/What went wrong/,/^$/p'
deployEu
deployUs
[EU] hello from dsl
[US] hello from dsl
[EU] bonjour from dsl
* What went wrong:
No matches
  Task 'deployAsia' not found in root project 'dsl'. Some candidates are: 'deployUs'.

The loop registered one task per region, so adding a region is a one-line change to gradle.properties. Asking for a task that doesn't exist fails before anything runs, with a hint, during the configuration phase.

Note: The script copies project.name into a val while configuring, and the task action only uses text. Touching project from inside a task action (doLast) works today but is an error once the configuration cache is on, because the cache doesn't keep the Project object. Capture what you need in a val or a provider first.

When the script doesn't compile

A typo in a build script is a Kotlin compile error, reported with file, line and column before any task runs:

bash · try it yourself
mkdir typo && cd typo
cat > settings.gradle.kts <<'KTS'
rootProject.name = "typo"
KTS
cat > build.gradle.kts <<'KTS'
plugins { java }
repositories { mavenCentral() }
dependencies { implementaton("org.apache.commons:commons-lang3:3.21.0") }
KTS
gradle -q help 2>&1 | sed -n '1p;/What went wrong/,/^1 error/p'
e: file:///home/learner/typo/build.gradle.kts:3:16: Unresolved reference 'implementaton'.
* What went wrong:
Script compilation error:

  Line 3: dependencies { implementaton("org.apache.commons:commons-lang3:3.21.0") }
                         ^ Unresolved reference 'implementaton'.

1 error

Kotlin DSL vs Groovy DSL

You'll still meet Groovy scripts in older projects and in documentation. The same build in both:

groovy
// build.gradle (Groovy DSL)
plugins { id 'java' }
dependencies { implementation 'org.apache.commons:commons-lang3:3.21.0' }
tasks.named('test') { useJUnitPlatform() }
kotlin
// build.gradle.kts (Kotlin DSL)
plugins { java }
dependencies { implementation("org.apache.commons:commons-lang3:3.21.0") }
tasks.named<Test>("test") { useJUnitPlatform() }

The differences are mostly syntax: parentheses and double quotes are required in Kotlin, and Kotlin wants types where Groovy guessed them. The Kotlin version's errors appear in the IDE as you type, rather than at run time.

Test yourself

Why do accessors such as java { } or tasks.test work only for plugins applied in the plugins {} block?

  1. They are written by hand
  2. Gradle generates them from that block before compiling the rest of the script
  3. They need a network connection
  4. They are Groovy-only

How do you override greeting=hello from gradle.properties for one build?

  1. -Dgreeting=hi
  2. -Pgreeting=hi
  3. --greeting hi
  4. Edit settings.gradle.kts

When is a build script's code executed?

  1. When each task runs
  2. During the configuration phase, before tasks execute
  3. Only on the first build
  4. At compile time of the Java sources