Gradle’s Kotlin DSL provides a pleasant editing experience in supported IDEs: content-assist, refactoring, documentation, and more.

IntelliJ IDEA and Android Studio
💡

This user manual and guides contain build script excerpts that demonstrate both the Groovy DSL and the Kotlin DSL. This is the best place where to find how to do this and what with the Gradle Kotlin DSL ; and it covers all Gradle features from using plugins to customizing the dependency resolution behavior.

If you are looking into migrating an existing build to the Gradle Kotlin DSL, please also check out the migration guide.

Prerequisites

  • The embedded Kotlin compiler is known to work on Linux, macOS, Windows, Cygwin, FreeBSD and Solaris on x86-64 architectures.

  • Knowledge of Kotlin syntax and basic language features is very helpful. The Kotlin reference documentation and Kotlin Koans should be useful to you.

  • Use of the plugins {} block to declare Gradle plugins significantly improves the editing experience, and is highly recommended.

Limitations

  • There are some situations where the Kotlin DSL is slower. First use, on clean checkouts or ephemeral CI agents for example, are known to be slower. The same applies to the scenario in which something in the buildSrc directory changes, which invalidates build-script caching. The main bottleneck is script compilation.

  • In IntelliJ IDEA, you must import your project from the Gradle model to get content-assist and refactoring tools for Kotlin DSL scripts.

  • The Kotlin DSL will not support model {} elements. This is part of the discontinued Gradle Software Model. Applying model rules from scripts is supported though, see the model-rules sample.

  • Enabling the incubating configuration on demand feature is not recommended as it can lead to very hard-to-diagnose problems.

  • Functions of the Gradle API taking Any that accept lazy constructs such as CopySpec.from(Any) don’t support Kotlin lambdas, use a Callable { .. } or a provider { .. } instead, see gradle/kotlin-dsl#1077.

If you run to trouble or a suspected bug, please take advantage of the gradle/kotlin-dsl issue tracker.

IDE support

Kotlin DSL is fully supported in Intellij IDEA and Android Studio. Other IDEs do not yet provide helpful tools for editing Gradle Kotlin DSL files, however, importing and working with Kotlin DSL-based builds work as usual.

Table 1. IDE support matrix
Build import Syntax highlighting 1 Semantic editor 2

IntelliJ IDEA

✓

✓

✓

Android Studio

✓

✓

✓

Eclipse IDE

✓

✓

✖

CLion

✓

✓

✖

Apache Netbeans

✓

✓

✖

Visual Studio Code (LSP)

✓

✓

✖

Visual Studio

✓

✖

✖

1 Kotlin syntax highlighting in Gradle Kotlin DSL scripts
2 code completion, navigation to sources, documentation, refactorings etc…​ in Gradle Kotlin DSL scripts

In IntelliJ IDEA, you must import your project from the Gradle model to get content-assist and refactoring tools for Kotlin DSL scripts.

In addition, IntelliJ IDEA and Android Studio might spawn up to 3 Gradle daemons when editing scripts; one per each type of script: project scripts, settings scripts and initialization scripts. Builds with slow configuration time might affect the IDE responsiveness, please check out the performance guide.

Automatic build import vs. automatic reload of script dependencies

Both IntelliJ IDEA and Android Studio will detect when you make changes to your build logic and offer suggestions as to what to do.

Both will suggest to re-import the whole build into the IDE:

IntelliJ IDEA
IntelliJ IDEA

Both will also suggest reloading script dependencies when editing a build script:

Reload script dependencies

It is recommended to disable automatic build import but enable automatic reload of script dependencies. That way you get early feedback while editing Gradle scripts while controlling when the whole build setup gets synchronized with your IDE.

Troubleshooting

The IDE support is provided by two components:

  • the IntelliJ IDEA or Android Studio Kotlin Plugin version,

  • the version of Gradle used to import the build.

In you run into trouble, the first thing to try is to run gradle tasks to see if your issue is IDE related only and to possibly get more details. If running Gradle works but your script editor is complaining then you can try restarting your IDE and invalidating its caches.

If, after trying the above, you suspect an issue with the .gradle.kts script editor you can:

  • run gradle tasks to get more details,

  • check logs in

    • $HOME/Library/Logs/gradle-kotlin-dsl on macos,

    • $HOME/.gradle-kotlin-dsl/logs on Linux,

    • $HOME/Application Data/gradle-kotlin-dsl/log on Windows,

  • and finally, open an issue on the gradle/kotlin-dsl issue tracker with as much detail as you can.

For IDE issues out of the .gradle.kts script editor, please open issues in the IDE issue tracker, respectively

Last but not least, if you face problems with Gradle itself or with the Gradle Kotlin DSL, please open issues on the corresponding issue tracker, respectively

Gradle Kotlin DSL scripts

Just like the Gradle Groovy DSL, the Gradle Kotlin DSL is implemented on top of the Java Gradle API. Everything you can read in a Gradle Kotlin DSL script is Kotlin code compiled and executed by Gradle. In Gradle Kotlin DSL scripts you write Kotlin code that uses objects, functions and properties from the Gradle API and applied Gradle plugins APIs.

Script file names

✨

Groovy DSL script files use the .gradle file name extension.

Kotlin DSL script files use the .gradle.kts file name extension.

To use the Kotlin DSL, simply name your files build.gradle.kts instead of build.gradle.

The settings file, settings.gradle, can also be renamed settings.gradle.kts.

In a multi-project build, you can have some modules using the Groovy DSL (with build.gradle) and others using the Kotlin DSL (with build.gradle.kts).

On top of that, apply the following conventions for better IDE support:

  • Name scripts that are applied to Settings according to the pattern *.settings.gradle.kts,

  • Name init scripts according to the pattern *.init.gradle.kts.

💡
Precompiled script plugins

The Gradle Kotlin DSL can also be used to author Gradle plugins as part of your local build logic or for published community or in-house plugins.

You can either write plugins in plain Kotlin (.kt files in src/main/kotlin) and make use of the Gradle Kotlin DSL API, or, use precompiled script plugins (.gradle.kts files in src/main/kotlin).

See the kotlin-dsl plugin section below for more information.

Implicit imports

All gradle.kts script has implicit imports comprised of:

⚠
Avoiding Gradle Kotlin DSL internal APIs

Use of Gradle Kotlin DSL internal APIs in plugins and build scripts has the potential to break builds when either Gradle or plugins change.

The Gradle Kotlin DSL extends the Gradle public API definition with org/gradle/kotlin/dsl/* excluding any subpackages.

Configuring plugins

Type-safe model accessors

Gradle Plugins contribute reusable and configurable models to a build. For example, the java plugin contributes artifact configurations such as implementation and testImplementation, it also adds a Gradle extension named sourceSets that can be used to configure and create source sets, it also registers Gradle tasks such as compileJava etc…​

Gradle scripts configure what applied plugins contribute to the build model. For example, adding dependencies or configuring dependency resolution on the implementation artifact configuration, changing the source directories for the main and test Java source sets, or, making compileJava fail on compiler warnings.

The Gradle Kotlin DSL provides a static Kotlin view over the dynamic model contributed by plugins in the form of type-safe model accessors.

✨
Configuration avoidance

Configuration avoidance was introduced in Gradle 4.9. It allows Gradle to avoid configuring unnecessary build logic, leading to faster build configuration time. See the corresponding Evolving the Gradle API to reduce configuration time blog post.

The Gradle Kotlin DSL embraces configuration avoidance by making the type-safe model accessors leverage the new APIs.

Where and when are type-safe model accessors available?

The Gradle Kotlin DSL currently supports type-safe model accessors for:

  • Artifact Configurations

  • Project Extensions and Conventions

  • Elements of the tasks container

  • Elements of Project Extensions that are containers

  • Extensions on each of the above

❗️

Only project build scripts have type-safe model accessors. Init scripts, settings scripts and applied script plugins don’t. Nor do precompiled script plugins. Theses limitations will be removed in a future Gradle release.

The set of type-safe model accessors available is calculated right before evaluating the script body, after the plugins {} block. It means that all model elements contributed after that point can not be reached with a type-safe model accessor. It also means that accessors for model elements contributed by plugins applied by parent projects are available.

Let’s look at a project build script that makes use of accessors:

Example 1. Using type-safe model accessors
build.gradle.kts
plugins {
    `java-library`
}

dependencies {                              (1)
    api("junit:junit:4.12")
    implementation("junit:junit:4.12")
    testImplementation("junit:junit:4.12")
}

configurations {                            (1)
    implementation {
        resolutionStrategy.failOnVersionConflict()
    }
}

sourceSets {                                (2)
    main {                                  (3)
        java.srcDir("src/core/java")
    }
}

java {                                      (4)
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11
}

tasks {
    test {                                  (5)
        testLogging.showExceptions = true
    }
}
  1. api, implementation and testImplementation artifact configurations contributed by the java-library plugin

  2. the sourceSets project extension contributed by the java-library plugin

  3. the main source set created by default by the java-library plugin

  4. the java project convention contributed by the java-library plugin

  5. the test task contributed by the java-library plugin

💡

Because your IDE knows about the accessors, it will include them when you ask your IDE for suggestions. This will happen both at the top level of your build scripts — most plugin extensions are added to the Project object — and within an extension’s configuration block.

Note that accessors for elements of containers such as configurations, tasks or sourceSets leverage Gradle’s configuration avoidance APIs. For example, on tasks they are of type TaskProvider<T> and provide a lazy reference and lazy configuration of the underlying task.

tasks.test {
    // lazy configuration
}

// Lazy reference
val testProvider: TaskProvider<SourceSet> = tasks.test

testProvider {
    // lazy configuration
}

// Eagerly realized Test task, defeat configuration avoidance if done out of a lazy context
val test: Test = tasks.test.get()

For all other containers, accessors for elements are of type NamedDomainObjectProvider<T> providing the same functionality.

What to do when type-safe model accessors are not available?

Following up on the sample build script shown above using the plugins {} block, here is the exact same build logic but using the imperative apply(plugin = "some.id"). Note that because imperative plugin application happens in the body of a build script, the model contributed by the plugin can not be made available as type-safe accessors.

Example 2. Configuring plugins without type-safe accessors
build.gradle.kts
apply(plugin = "java-library")

dependencies {
    "api"("junit:junit:4.12")
    "implementation"("junit:junit:4.12")
    "testImplementation"("junit:junit:4.12")
}

configurations {
    "implementation" {
        resolutionStrategy.failOnVersionConflict()
    }
}

configure<SourceSetContainer> {
    named("main") {
        java.srcDir("src/core/java")
    }
}

configure<JavaPluginConvention> {
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11
}

tasks {
    named<Test>("test") {
        testLogging.showExceptions = true
    }
}
💡
All models contributed by plugins are reachable via the API.

In some circumstances, type-safe accessors are not available: imperative configuration (apply(plugin = "id") or configuration of model elements created in the same script), script plugins (apply(from = "script-plugin.gradle.kts")), cross project configuration (see below), Gradle plugins implemented in Kotlin and precompiled script plugins (see below).

Whenever you can’t find a type-safe accessor you should fallback to using the API.

Using the API instead of accessors to configure plugins is not that different, a bit more verbose though. It also requires knowing names and/or types of the configured model elements. We’ll now see how those can be discovered by looking at the script above in details.

Let’s start with artifact configurations.

Example 3. Artifact configurations
build.gradle.kts
apply(plugin = "java-library")

dependencies {
    "api"("junit:junit:4.12")
    "implementation"("junit:junit:4.12")
    "testImplementation"("junit:junit:4.12")
}

configurations {
    "implementation" {
        resolutionStrategy.failOnVersionConflict()
    }
}

Artifact configurations have a name. Here, instead of using an accessor we refer to them by name using string literals.

One can discover what artifact configurations are available by either looking at the java-library plugin documentation, source code or by running gradle dependencies.

Now let’s look at Project extensions and conventions.

Example 4. Project extensions and conventions
build.gradle.kts
apply(plugin = "java-library")

configure<SourceSetContainer> {
    named("main") {
        java.srcDir("src/core/java")
    }
}

configure<JavaPluginConvention> {
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11
}

Project extensions and conventions have a name and a type. Here, instead of using the sourceSets and java accessors we use the configure<T> {} function to refer to them by type and apply a configuration block. sourceSets is a Gradle extension on Project of type SourceSetContainer. java is a Gradle convention on Project of type JavaPluginConvention.

One can discover what extensions and conventions are available by either looking at the applied plugins documentation, source code or by running gradle kotlinDslAccessorsReport which prints the Kotlin code for accessing the model elements contributed by applied plugins providing names and types.

Note that you can also use the the<T>() function if you only need a reference to the extension or convention or for one liners:

the<SourceSetContainer>()["main"].srcDir("src/core/java")

The snippet above also configures the existing element of the source set container named main:

Example 5. Elements of Project extensions that are containers
build.gradle.kts
apply(plugin = "java-library")

configure<SourceSetContainer> {
    named("main") {
        java.srcDir("src/core/java")
    }
}

Source sets have a name. Here, instead of using the main accessor we use the Gradle API and refer to it by name using a string literal.

One can discover what source sets, or what existing elements are present in any container, by either looking at the applied plugins documentation, source code or by running gradle kotlinDslAccessorsReport which prints the Kotlin code for accessing the model elements contributed by applied plugins providing names and types.

This is very similar to what our sample build script does to configure a task:

Example 6. Tasks
build.gradle.kts
apply(plugin = "java-library")

tasks {
    named<Test>("test") {
        testLogging.showExceptions = true
    }
}

Gradle tasks have a name and a type. Here, instead of using an accessor we use the Gradle API and refer to them by name and type. Note that it’s necessary to specify the type of the task explicitly. Otherwise, the script won’t compile because the inferred type will be Task, not Test, and the testLogging property is specific to the Test task type. You can, however, omit the type if you only need to configure properties or call methods that are common to all tasks, i.e. they are declared on the Task interface:

One can discover what tasks are available by running gradle tasks, and then to know the type of a given task by running gradle help --task taskName:

❯ ./gradlew help --task test
...
Type
     Test (org.gradle.api.tasks.testing.Test)

Note that the IDE can assist us with the required imports, so we only need the simple names, i.e. without the full packages. In this case, no need for an import, the Test task type is part of the Gradle API and of implicit imports.

About conventions

Some of the Gradle core plugins expose configurability with the help of a so-called Convention. The Convention concept precedes that of extension and serves a similar purpose. Please avoid using the Convention concept when writing new plugins. The long term plan is to migrate all Gradle core plugins to use extensions and remove the Convention concept altogether.

As seen above, the Gradle Kotlin DSL provides accessors only for Conventions on Project. There are situations that require you to interact with a Gradle plugin that uses Conventions on other objects. The most common example is configuring source sets conventions. The Gradle Kotlin DSL provides the withConvention(T::class) {} extension function to do so:

Example 7. Configuring source set conventions
build.gradle.kts
plugins {
    groovy
}

sourceSets {
    main {
        withConvention(GroovySourceSet::class) {
            groovy.srcDir("src/core/groovy")
        }
    }
}

Multi-project builds (e.g. Android)

Multi-project builds are very common. Android builds are, for example, multi-project builds from the start. When creating a new build from Android Studio it creates a multi-project build.

To get the most benefits of the Gradle Kotlin DSL you should strive to keep your build scripts declarative. The main thing to remember here is that in order to get type-safe accessors, plugins must be applied before the body of build scripts. As seen above, this can be achieved by using the plugins {} block.

Applying plugins

In multi-project builds you should centrally declare plugin dependencies in the root project build file, specifying the version. This always allow for applying the plugins in sub projects build scripts using the plugins {} block.

It is recommended to do so using the plugins {} block in your root project build script as documented in the Using Gradle plugins chapter:

Example 8. Declare plugin dependencies in the root build script using the plugins {} block
settings.gradle.kts
rootProject.name = "multi-project-build"
include("domain", "infra", "http")
build.gradle.kts
plugins {
    id("com.github.johnrengelman.shadow") version "4.0.1" apply false
    id("io.ratpack.ratpack-java") version "1.5.4" apply false
}
domain/build.gradle.kts
plugins {
    `java-library`
}

dependencies {
    api("javax.measure:unit-api:1.0")
    implementation("tec.units:unit-ri:1.0.3")
}
infra/build.gradle.kts
plugins {
    `java-library`
    id("com.github.johnrengelman.shadow")
}

shadow {
    applicationDistribution.from("src/dist")
}

tasks.shadowJar {
    minimize()
}
http/build.gradle.kts
plugins {
    java
    id("io.ratpack.ratpack-java")
}

dependencies {
    implementation(project(":domain"))
    implementation(project(":infra"))
    implementation(ratpack.dependency("dropwizard-metrics"))
}

application {
    mainClassName = "example.App"
}

ratpack.baseDir = file("src/ratpack/baseDir")

If your build requires additional plugin repositories, they should be declared in the pluginManagement {} block in your settings.gradle.kts file:

Example 9. Declare additional plugin repositories
settings.gradle.kts
pluginManagement {
    repositories {
        jcenter()
        gradlePluginPortal()
    }
}

Plugins fetched from a source other than the Gradle Plugin Portal can only be requested using the plugins {} block if they were published with their plugin marker artifacts.

For example, the Android Plugin for Gradle present in the google() repository is published without plugin marker artifacts, at least up to version 3.2.0 of the plugin. Please star the corresponding Google issue.

In that case, you can fall back to declaring your plugin dependencies using the buildscript {} block in the root project build script:

Example 10. Declare plugin dependencies in the root build script using the buildscript {} block
settings.gradle.kts
include("lib", "app")
build.gradle.kts
buildscript {
    repositories {
        google()
        gradlePluginPortal()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.2.0")
    }
}
lib/build.gradle.kts
plugins {
    id("com.android.library")
}

android {
    // ...
}
app/build.gradle.kts
plugins {
    id("com.android.application")
}

android {
    // ...
}

It’s not that different from what Android Studio produces when creating a new build. The main difference is that sub projects build scripts apply plugins using the plugins {} block.

If you want to use a plugin that can’t be applied using the plugins {} block directly in your root project or in a single project build, see the dedicated section below.

Cross-configuring projects

You might want to cross-configure projects, for example configuring sub projects from the root project build script. In that case, you won’t have the help of the type-safe accessors for model elements contributed by the plugins and have to rely on string literals and the API.

For the sake of the example, let’s look at the same Java/Ratpack build as above but fully configured from the root build script:

Example 11. Cross-configuring projects
settings.gradle.kts
rootProject.name = "multi-project-build"
include("domain", "infra", "http")
build.gradle.kts
import com.github.jengelman.gradle.plugins.shadow.ShadowExtension
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import ratpack.gradle.RatpackExtension

plugins {
    id("com.github.johnrengelman.shadow") version "4.0.1" apply false
    id("io.ratpack.ratpack-java") version "1.5.4" apply false
}

project(":domain") {
    apply(plugin = "java-library")
    dependencies {
        "api"("javax.measure:unit-api:1.0")
        "implementation"("tec.units:unit-ri:1.0.3")
    }
}

project(":infra") {
    apply(plugin = "java-library")
    apply(plugin = "com.github.johnrengelman.shadow")
    configure<ShadowExtension> {
        applicationDistribution.from("src/dist")
    }
    tasks.named<ShadowJar>("shadowJar") {
        minimize()
    }
}

project(":http") {
    apply(plugin = "java")
    apply(plugin = "io.ratpack.ratpack-java")
    val ratpack = the<RatpackExtension>()
    dependencies {
        "implementation"(project(":domain"))
        "implementation"(project(":infra"))
        "implementation"(ratpack.dependency("dropwizard-metrics"))
        "runtime"("org.slf4j:slf4j-simple:1.7.25")
    }
    configure<ApplicationPluginConvention> {
        mainClassName = "example.App"
    }
    ratpack.baseDir = file("src/ratpack/baseDir")
}

It’s more verbose and requires more gymnastics to write but it works and can be useful. See the Configuring plugins section above for a detailed explanation.

Plugins not usable in plugins {}

Plugins fetched from a source other than the Gradle Plugin Portal may or may not be usable with the plugins {} block. It depends on how they have been published.

If your build is a multi-project build and you don’t need to apply such a plugin to your root project, see the dedicated section above. Otherwise, keep reading.

The Android Plugin for Gradle, for example, is not published to the Gradle Plugin Portal and at least up to version 3.2.0 of the plugin, the metadata required to resolve the artifacts for a given plugin identifier is not published to the Google repository.

We will show you in this section how to apply the Android Plugin to your single or root project.

✨
When publishing plugins, please use Gradle’s built-in Java Gradle Plugin Plugin. It automates the publication of the metadata necessary to make your plugins usable with the plugins {} block.

The goal is to instruct your build on how to map the com.android.application plugin identifier to a resolvable artifact. This is done in two steps:

  • Add a plugin repository to the build’s settings file

  • Map the plugin ID to the corresponding artifact coordinates

This happens in the settings file within the pluginManagement {} block. The following sample maps the com.android.application ID to the com.android.tools.build:gradle:<version> artifact available in the google() repository:

Example 12. Mapping plugin IDs to dependency coordinates
settings.gradle.kts
pluginManagement {
    repositories {
        google()
        gradlePluginPortal()
    }
    resolutionStrategy {
        eachPlugin {
            if(requested.id.namespace == "com.android") {
                useModule("com.android.tools.build:gradle:${requested.version}")
            }
        }
    }
}
build.gradle.kts
plugins {
    id("com.android.application") version "3.2.0"
}

android {
    // ...
}

See the Plugin Management section of the Gradle user manual for more information.

In the case of a multi-project build, the above is very similar to using buildscript { dependencies { classpath(..) } } in your root project build script to depend on third party plugins and then using plugins {} in your sub project build scripts to apply them. The main difference is that the root project can also benefit from the plugins {} block and it is more aligned with Gradle best practices.

The same approach can be used to resolve plugins from composite builds, which do not expose plugin markers yet. Simply map the plugin ID to the corresponding artifact coordinates as shown in the Android samples above.

Working with containers

The Gradle build model makes heavy use of containers. For example, Gradle core contributes configurations which is a container of Configuration objects and tasks which is a container of Task objects; core plugins such as java and distribution contribute containers such as sourceSets and distributions. Community plugins also contribute containers, such as android.buildTypes contributed by the android plugin. Gradle plugins create containers using Project.container<Type>().

💡

Note that if you are configuring existing elements on supported containers you can leverage the type-safe accessors as described in the Configuring plugins section above.

The Gradle Kotlin DSL provides build authors with uniform ways of interacting with containers. We already saw some examples configuring source sets or tasks in the Configuring plugins section above. Let’s now look in detail at how to interact with containers using the Gradle Kotlin DSL by using the tasks container as an example.

Using the containers API

All the containers implement NamedDomainObjectContainer<DomainObjectType>, some of them can contain objects of different types and implement PolymorphicDomainObjectContainer<BaseType>. The first and simplest way to interact with containers is through their API.

Example 13. Using the containers API
build.gradle.kts
tasks.named("check")                    (1)
tasks.register("myTask1")               (2)

tasks.named<JavaCompile>("compileJava") (3)
tasks.register<Copy>("myCopy1")         (4)

tasks.named("assemble") {               (5)
    dependsOn(":myTask1")
}
tasks.register("myTask2") {             (6)
    description = "Some meaningful words"
}

tasks.named<Test>("test") {             (7)
    testLogging.showStackTraces = true
}
tasks.register<Copy>("myCopy2") {       (8)
    from("source")
    into("destination")
}
  1. gets a reference to the existing task named check

  2. registers a new task named myTask1

  3. gets a reference to the existing task named compileJava of type JavaCompile

  4. registers a new task named myCopy1 of type Copy

  5. gets a reference to the existing task named assemble and configures it

  6. registers a new task named myTask2 and configures it

  7. gets a reference to the existing task named test of type Test and configures it

  8. registers a new task named myCopy2 of type Copy and configures it

✨

The above rely on configuration avoidance APIs. If you need to eagerly configure or register container elements simply replace named with getByName and register with create.

Via Kotlin delegated properties

Another way to interact with containers is via Kotlin delegated properties that are particularly useful if you need a reference to a container element for further usage. By not using string literals for the element names, Kotlin delegated properties allow for easy renaming via IDE refactorings. The sample below does the exact same things as the one in the section above, reusing references to tasks instead of using task paths in string literals:

Example 14. Via Kotlin delegated properties
build.gradle.kts
val check by tasks.existing
val myTask1 by tasks.registering

val compileJava by tasks.existing(JavaCompile::class)
val myCopy1 by tasks.registering(Copy::class)

val assemble by tasks.existing {
    dependsOn(myTask1)
}
val myTask2 by tasks.registering {
    description = "Some meaningful words"
}

val test by tasks.existing(Test::class) {
    testLogging.showStackTraces = true
}
val myCopy2 by tasks.registering(Copy::class) {
    from("source")
    into("destination")
}
✨

The above rely on configuration avoidance APIs. If you need to eagerly configure or register container elements simply replace existing with getting and registering with creating.

In a container scope

When configuring several elements of a container one can group interactions in a block in order not to repeat the container’s name on each interaction. The following example mixes the usage of type-safe accessors, the container API and Kotlin delegated properties:

Example 15. Container scope
build.gradle.kts
tasks {
    test {
        testLogging.showStackTraces = true
    }
    val myCheck by registering {
        doLast { /* assert on something meaningful */ }
    }
    check {
        dependsOn(myCheck)
    }
    register("myHelp") {
        doLast { /* do something helpful */ }
    }
}

Working with properties

The Gradle Kotlin DSL also provides some sugar on top of the Gradle API for working with properties.

Gradle, Settings & Project properties

Gradle, Settings and Project properties are documented in the Build Environment chapter.

They can also be used via Kotlin delegated properties, see the sample below for Project properties:

build.gradle.kts
val myProperty: String by project
val myNullableProperty: String? by project

It works the exact same way in settings scripts for Settings properties and in init scripts for Gradle properties, respectively replacing by project with by settings or by gradle.

Extra properties

Extra properties are documented in the Writing Build Scripts chapter.

On every ExtensionAware type they can be used via the extra property as a Kotlin delegated property, see the sample below.

build.gradle.kts
// Define new extra properties
val myNewProperty by extra("initial value")
val myOtherNewProperty by extra { "lazy initial value" }

// Reference existing extra properties
val myProperty: String by extra
val myNullableProperty: String? by extra

Let’s say the snippet above is from your root project build script, in order to reference the myNewProperty from a sub project you’d do:

my-sub-project/build.gradle.kts
val myNewProperty: String by rootProject.extra

It works the same way in settings or init scripts.

All ExtensionAware types can host extra properties, Task is a common example:

build.gradle.kts
tasks {
    test {
        // Define new extra properties
        val myNewTaskProperty by extra("initial value")
        val myOtherNewTaskProperty by extra { "lazy initial value" }

        // Reference existing extra properties
        val myTaskProperty: String by extra
        val myNullableTaskProperty: String? by extra
    }
}

The kotlin-dsl plugin

When applied to a project, the kotlin-dsl Gradle plugin configures the project’s Kotlin source sets to enable Gradle Kotlin DSL features.

It is useful for all projects implementing build logic: buildSrc, included builds for build logic or Gradle plugin builds.

Example 16. Apply the kotlin-dsl plugin to buildSrc
buildSrc/build.gradle.kts
plugins {
    `kotlin-dsl`
}

repositories {
    // The org.jetbrains.kotlin.jvm plugin requires a repository
    // where to download the Kotlin compiler dependencies from.
    jcenter()
}

The kotlin-dsl plugin

  • applies the org.jetbrains.kotlin.jvm plugin,

  • configures an embedded repository that contains all Kotlin libraries embedded with the Gradle Kotlin DSL,

  • adds the kotlin-stdlib-jdk8, kotlin-reflect and gradleKotlinDsl() dependencies to the compileOnly and testImplementation configurations,

  • configures the Kotlin compiler with the same set of Kotlin compiler settings that is used for Gradle Kotlin DSL scripts,

  • and, enables precompiled script plugins, see below.

⚠

The kotlin-dsl plugin enables experimental Kotlin compiler features. See the Kotlin compiler arguments section below for more information.

By default, the kotlin-dsl plugin warns about using experimental features of the Kotlin compiler. You can silence the warning by setting the experimentalWarning property of the kotlinDslPluginOptions extension to false as follows:

Example 17. Disable experimental Kotlin compiler features warning
buildSrc/build.gradle.kts
plugins {
    `kotlin-dsl`
}

kotlinDslPluginOptions {
    experimentalWarning.set(false)
}

Precompiled script plugins

The kotlin-dsl plugin can be used to author Gradle plugins as part of your local build logic or for published community or in-house plugins. You can write plugins in plain Kotlin (.kt files in src/main/kotlin) making use of the gradleKotlinDsl() API, and, use precompiled script plugins (.gradle.kts files in src/main/kotlin).

Precompiled script plugins are Gradle Kotlin DSL scripts compiled as part of a regular Kotlin source-set and distributed in the usual way, as java class files packaged in some library, meant to be consumed as a binary Gradle plugin. They follow the same file name conventions, are compiled with the same Kotlin compiler settings, and plugin metadata is generated for each one of them thanks to the integration with the java-gradle-plugin. They can then be applied by plugin ID like any other plugin.

The Gradle plugin ID by which the precompiled script can be referenced is derived from its name and optional package declaration.

Thus, the script src/main/kotlin/java-library-convention.gradle.kts is exposed as the java-library-convention plugin (assuming it has no package declaration) whereas the script src/main/kotlin/my/java-library-convention.gradle.kts is exposed as the my.java-library-convention plugin, again assuming it has the matching package declaration.

Let’s walk through the steps needed to implement a plugin in buildSrc using a precompiled script plugin.

First, you need a buildSrc/build.gradle.kts file applying the kotlin-dsl plugin:

Example 18. Apply the kotlin-dsl plugin to buildSrc
buildSrc/build.gradle.kts
plugins {
    `kotlin-dsl`
}

buildSrc being a separate build, don’t forget to add a buildSrc/settings.gradle.kts file. It can be empty.

Then create the new java-library-convention.gradle.kts file in buildSrc/src/main/kotlin:

Example 19. A java-library convention plugin
buildSrc/src/main/kotlin/java-library-convention.gradle.kts
plugins {
    `java-library`
    checkstyle
}

configure<JavaPluginConvention> {
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11
}

configure<CheckstyleExtension> {
    maxWarnings = 0
    // ...
}

tasks.withType<JavaCompile> {
    options.isWarnings = true
    // ...
}

dependencies {
    "testImplementation"("junit:junit:4.12")
    // ...
}
❗️

Precompiled script plugins do not get type-safe accessors. This limitation will be lifted in a future Gradle release.

The precompiled script plugin can then be applied to the root project as follows:

Example 20. Apply the java-library-convention plugin
build.gradle.kts
plugins {
    id("java-library-convention")
}

Embedded Kotlin

Gradle embeds Kotlin in order to provide support for Kotlin based scripts.

Kotlin versions

Gradle ships with kotlin-compiler-embeddable plus matching versions of kotlin-stdlib and kotlin-reflect libraries. For example, Gradle 4.3 ships with the Gradle Kotlin DSL v0.12.1 that includes Kotlin 1.1.51 versions of these modules. The kotlin package from those modules is visible through the Gradle classpath.

The compatibility guarantees provided by Kotlin apply for both backward and forward compatibility.

Backward compatibility

Our approach is to only do backwards-breaking Kotlin upgrades on a major Gradle release. We will always clearly document which Kotlin version we ship and announce upgrade plans before a major release.

Plugin authors who want to stay compatible with older Gradle versions need to limit their API usage to a subset that is compatible with these old versions. It’s not really different from any other new API in Gradle. E.g. if we introduce a new API for dependency resolution and a plugin wants to use that API, then they either need to drop support for older Gradle versions or they need to do some clever organization of their code to only execute the new code path on newer versions.

Forward compatibility

The biggest issue is the compatibility between the external kotlin-gradle-plugin version and the kotlin-stdlib version shipped with Gradle. More generally, between any plugin that transitively depends on kotlin-stdlib and its version shipped with Gradle. As long as the combination is compatible everything should work. This will become less of an issue as the language matures.

Kotlin compiler arguments

These are the Kotlin compiler arguments used for compiling Gradle Kotlin DSL scripts and Kotlin sources and scripts in a project that has the kotlin-dsl plugin applied:

-jvm-target=1.8

Sets the target version of the generated JVM bytecode to 1.8.

-Xjsr305=strict

Sets up Kotlin’s Java interoperability to strictly follow JSR-305 annotations for increased null safety. See Calling Java code from Kotlin in the Kotlin documentation for more information.

-XX:NewInference

Enables the experimental Kotlin compiler inference engine (required for SAM conversion for Kotlin functions).

-XX:SamConversionForKotlinFunctions

Enables SAM (Single Abstract Method) conversion for Kotlin functions in order to allow Kotlin build logic to expose and consume org.gradle.api.Action<T> based APIs. Such APIs can then be used uniformly from both the Kotlin and Groovy DSLs.

As an example, given the following hypothetical Kotlin function with a Java SAM parameter type:

fun kotlinFunctionWithJavaSam(action: org.gradle.api.Action<Any>) = TODO()

SAM conversion for Kotlin functions enables the following usage of the function:

kotlinFunctionWithJavaSam {
    // ...
}

Without SAM conversion for Kotlin functions one would have to explicitly convert the passed lambda:

kotlinFunctionWithJavaSam(Action {
    // ...
})

Interoperability

When mixing languages in your build logic, you may have to cross language boundaries. An extreme example would be a build that uses tasks and plugins that are implemented in Java, Groovy and Kotlin, while also using both Kotlin DSL and Groovy DSL build scripts.

Quoting the Kotlin reference documentation:

Kotlin is designed with Java Interoperability in mind. Existing Java code can be called from Kotlin in a natural way, and Kotlin code can be used from Java rather smoothly as well.

Both calling Java from Kotlin and calling Kotlin from Java are very well covered in the Kotlin reference documentation.

The same mostly applies to interoperability with Groovy code. In addition, the Kotlin DSL provides several ways to opt into Groovy semantics, which we look at next.

Static extensions

Both the Groovy and Kotlin languages support extending existing classes via Groovy Extension modules and Kotlin extensions.

To call a Kotlin extension function from Groovy, call it as a static function, passing the receiver as the first parameter:

Example 21. Call Kotlin extension from Groovy
build.gradle
TheTargetTypeKt.kotlinExtensionFunction(receiver, "parameters", 42, aReference)

Kotlin extension functions are package-level functions and you can learn how to locate the name of the type declaring a given Kotlin extension in see the Package-Level Functions section of the Kotlin reference documentation.

To call a Groovy extension method from Kotlin, the same approach applies: call it as a static function passing the receiver as the first parameter. Here’s an example:

Example 22. Call Groovy extension from Kotlin
build.gradle.kts
TheTargetTypeGroovyExtension.groovyExtensionMethod(receiver, "parameters", 42, aReference)

Named parameters and default arguments

Both the Groovy and Kotlin languages support named function parameters and default arguments, although they are implemented very differently. Kotlin has fully-fledged support for both, as described in the Kotlin language reference under named arguments and default arguments. Groovy implements named arguments in a non-type-safe way based on a Map<String, ?> parameter, which means they cannot be combined with default arguments. In other words, you can only use one or the other in Groovy for any given method.

Calling Kotlin from Groovy

To call a Kotlin function that has named arguments from Groovy, just use a normal method call with positional parameters. There is no way to provide values by argument name.

To call a Kotlin function that has default arguments from Groovy, always pass values for all the function parameters.

Calling Groovy from Kotlin

To call a Groovy function with named arguments from Kotlin, you need to pass a Map<String, ?>, as shown in this example:

Example 23. Call Groovy function with named arguments from Kotlin
build.gradle.kts
groovyNamedArgumentTakingMethod(mapOf(
    "parameterName" to "value",
    "other" to 42,
    "and" to aReference))

To call a Groovy function with default arguments from Kotlin, always pass values for all the parameters.

Groovy closures from Kotlin

You may sometimes have to call Groovy methods that take Closure arguments from Kotlin code. For example, some third-party plugins written in Groovy expect closure arguments.

✨
Gradle plugins written in any language should prefer the type Action<T> type in place of closures. Groovy closures and Kotlin lambdas are automatically mapped to arguments of that type.

In order to provide a way to construct closures while preserving Kotlin’s strong typing, two helper methods exist:

  • closureOf<T> {}

  • delegateClosureOf<T> {}

Both methods are useful in different circumstances and depend upon the method you are passing the Closure instance into.

Some plugins expect simple closures, as with the Bintray plugin:

Example 24. Use closureOf<T> {}
build.gradle.kts
bintray {
    pkg(closureOf<PackageConfig> {
        // Config for the package here
    })
}

In other cases, like with the Gretty Plugin when configuring farms, the plugin expects a delegate closure:

Example 25. Use delegateClosureOf<T> {}
build.gradle.kts
farms {
    farm("OldCoreWar", delegateClosureOf<FarmExtension> {
        // Config for the war here
    })
}

There sometimes isn’t a good way to tell, from looking at the source code, which version to use. Usually, if you get a NullPointerException with closureOf<T> {}, using delegateClosureOf<T> {} will resolve the problem.

These two utility functions are useful for configuration closures, but some plugins might expect Groovy closures for other purposes. The KotlinClosure0 to KotlinClosure2 types allows adapting Kotlin functions to Groovy closures with more flexibility.

Example 26. Use KotlinClosureX types
build.gradle.kts
somePlugin {

    // Adapt parameter-less function
    takingParameterLessClosure(KotlinClosure0({
        "result"
    }))

    // Adapt unary function
    takingUnaryClosure(KotlinClosure1<String, String>({
        "result from single parameter $this"
    }))

    // Adapt binary function
    takingBinaryClosure(KotlinClosure2<String, String, String>({ a, b ->
        "result from parameters $a and $b"
    }))
}

Also see the groovy-interop sample.

The Kotlin DSL Groovy Builder

If some plugin makes heavy use of Groovy metaprogramming, then using it from Kotlin or Java or any statically-compiled language can be very cumbersome.

The Kotlin DSL provides a withGroovyBuilder {} utility extension that attaches the Groovy metaprogramming semantics to objects of type Any. The following example demonstrates several features of the method on the object target:

Example 27. Use withGroovyBuilder {}
build.gradle.kts
target.withGroovyBuilder {                                          (1)

    // GroovyObject methods available                               (2)
    val foo = getProperty("foo")
    setProperty("foo", "bar")
    invokeMethod("name", arrayOf("parameters", 42, aReference))

    // Kotlin DSL utilities
    "name"("parameters", 42, aReference)                            (3)
        "blockName" {                                               (4)
            // Same Groovy Builder semantics on `blockName`
        }
    "another"("name" to "example", "url" to "https://example.com/") (5)
}
  1. The receiver is a GroovyObject and provides Kotlin helpers

  2. The GroovyObject API is available

  3. Invoke the methodName method, passing some parameters

  4. Configure the blockName property, maps to a Closure taking method invocation

  5. Invoke another method taking named arguments, maps to a Groovy named arguments Map<String, ?> taking method invocation

The maven-plugin sample demonstrates the use of the withGroovyBuilder() utility extensions for configuring the uploadArchives task to deploy to a Maven repository with a custom POM using Gradle’s core Maven Plugin. Note that the recommended Maven Publish Plugin provides a type-safe and Kotlin-friendly DSL that allows you to easily do the same and more without resorting to withGroovyBuilder().

Using a Groovy script

Another option when dealing with problematic plugins that assume a Groovy DSL build script is to configure them in a Groovy DSL build script that is applied from the main Kotlin DSL build script:

Example 28. Using a Groovy script
build.gradle.kts
plugins {
    id("dynamic-groovy-plugin") version "1.0"               (1)
}
apply(from = "dynamic-groovy-plugin-configuration.gradle")  (2)
dynamic-groovy-plugin-configuration.gradle
native {                                                    (3)
    dynamic {
        groovy as Usual
    }
}
  1. The Kotlin build script requests and applies the plugin

  2. The Kotlin build script applies the Groovy script

  3. The Groovy script uses dynamic Groovy to configure plugin