W3cubDocs

/Kotlin

Using Gradle

In order to build a Kotlin project with Gradle, you should set up the kotlin-gradle plugin, apply it to your project and add kotlin-stdlib dependencies. Those actions may also be performed automatically in IntelliJ IDEA by invoking Tools | Kotlin | Configure Kotlin in Project action.

Plugin and Versions

Apply the Kotlin Gradle plugin by using the Gradle plugins DSL. The Kotlin Gradle plugin 1.3.41 works with Gradle 4.1 and later.

plugins {
    id 'org.jetbrains.kotlin.<...>' version '1.3.41'
}
plugins {
    kotlin("<...>") version "1.3.41"
}

The placeholder <...> should be replaced with one of the plugin names that can be found in further sections.

Alternatively, apply plugin by adding the kotlin-gradle-plugin dependency to the build script classpath:

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.41"
    }
}

plugins {
    id "org.jetbrains.kotlin.<...>" version "1.3.41"
}
buildscript {
    repositories {
            mavenCentral()
    }
        
    dependencies {
        classpath(kotlin("gradle-plugin", version = "1.3.41"))
    }
}
plugins {
    kotlin("<...>")
}

This is not required when using Kotlin Gradle plugin 1.1.1 and above with the Gradle plugins DSL, and with Gradle Kotlin DSL.

Building Kotlin Multiplatform Projects

Using the kotlin-multiplatform plugin for building multiplatform projects is described in Building Multiplatform Projects with Gradle.

Targeting the JVM

To target the JVM, apply the Kotlin JVM plugin. Starting with Kotlin 1.1.1, the plugin can be applied using the Gradle plugins DSL:

plugins {
    id "org.jetbrains.kotlin.jvm" version "1.3.41"
}
plugins {
    kotlin("jvm") version "1.3.41"
}

The version should be literal in this block, and it cannot be applied from another build script.

Alternatively, you can use the older apply plugin approach:

apply plugin: 'kotlin'

It's not recommended to apply Kotlin plugins with apply in Gradle Kotlin DSL. The details are provided below.

Kotlin sources can be mixed with Java sources in the same folder, or in different folders. The default convention is using different folders:

project
    - src
        - main (root)
            - kotlin
            - java

The corresponding sourceSets property should be updated if not using the default convention:

sourceSets {
    main.kotlin.srcDirs += 'src/main/myKotlin'
    main.java.srcDirs += 'src/main/myJava'
}
sourceSets["main"].java.srcDir("src/main/myJava")
sourceSets["main"].withConvention(KotlinSourceSet::class) {    
    kotlin.srcDir("src/main/myKotlin") 
}

With Gradle Kotlin DSL, configure source sets with java.sourceSets { ... } instead.

Targeting JavaScript

When targeting JavaScript, a different plugin should be applied:

plugins {
    id 'kotlin2js' version '1.3.41'
}
plugins {
    id("kotlin2js") version "1.3.41"
}

Note that this way of applying the Kotlin/JS plugin requires adding the following code to Gradle settings file (settings.gradle):

pluginManagement {
    resolutionStrategy {
        eachPlugin {
            if (requested.id.id == "kotlin2js") {
                useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${requested.version}")
            }
        }
    }
}

This plugin only works for Kotlin files so it is recommended to keep Kotlin and Java files separate (in case if the same project contains Java files). As with targeting the JVM, if not using the default convention, you should specify the source folder using sourceSets:

sourceSets {
    main.kotlin.srcDirs += 'src/main/myKotlin'
}
sourceSets["main"].withConvention(KotlinSourceSet::class) {    
    kotlin.srcDir("src/main/myKotlin") 
}

In addition to the output JavaScript file, the plugin by default creates an additional JS file with binary descriptors. This file is required if you're building a reusable library that other Kotlin modules can depend on, and should be distributed together with the result of translation. The generation is controlled by the kotlinOptions.metaInfo option:

compileKotlin2Js {
    kotlinOptions.metaInfo = true
}
tasks {
    "compileKotlin2Js"(Kotlin2JsCompile::class)  {
        kotlinOptions.metaInfo = true
    }
}

Targeting Android

Android's Gradle model is a little different from ordinary Gradle, so if we want to build an Android project written in Kotlin, we need kotlin-android plugin instead of kotlin:

buildscript {
    ext.kotlin_version = '1.3.41'

    ...

    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}
buildscript {
    dependencies {
        classpath("com.android.tools.build:gradle:3.2.1")
        classpath(kotlin("gradle-plugin", version = "1.3.41"))
    }
}
plugins {
    id("com.android.application")
    id("kotlin-android")
}

Kotlin Gradle plugin 1.3.41 works with Android Gradle Plugin 3.0 and later.

Don't forget to configure the standard library dependency.

Android Studio

If using Android Studio, the following needs to be added under android:

android {
  ...

  sourceSets {
    main.java.srcDirs += 'src/main/kotlin'
  }
}
android {
  ...
  
    sourceSets["main"].java.srcDir("src/main/kotlin")
}

This lets Android Studio know that the kotlin directory is a source root, so when the project model is loaded into the IDE it will be properly recognized. Alternatively, you can put Kotlin classes in the Java source directory, typically located in src/main/java.

Configuring Dependencies

In addition to the kotlin-gradle-plugin dependency shown above, you need to add a dependency on the Kotlin standard library:

repositories {
    mavenCentral()
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib"
}
repositories {
    mavenCentral()
}

dependencies {
    implementation(kotlin("stdlib"))
}

The Kotlin standard library kotlin-stdlib targets Java 6 and above. There are extended versions of the standard library that add support for some of the features of JDK 7 and JDK 8. To use these versions, add one of the following dependencies instead of kotlin-stdlib:

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
implementation(kotlin("stdlib-jdk7"))
implementation(kotlin("stdlib-jdk8"))

In Kotlin 1.1.x, use kotlin-stdlib-jre7 and kotlin-stdlib-jre8 instead.

If you target JavaScript, use the stdlib-js dependency.

implementation "org.jetbrains.kotlin:kotlin-stdlib-js"
implementation(kotlin("stdlib-js"))

If your project uses Kotlin reflection or testing facilities, you need to add the corresponding dependencies as well:

implementation "org.jetbrains.kotlin:kotlin-reflect"
testImplementation "org.jetbrains.kotlin:kotlin-test"
testImplementation "org.jetbrains.kotlin:kotlin-test-junit"
implementation(kotlin("reflect"))
testImplementation(kotlin("test"))
testImplementation(kotlin("test-junit"))

Starting with Kotlin 1.1.2, the dependencies with group org.jetbrains.kotlin are by default resolved with the version taken from the applied plugin. You can provide the version manually using the full dependency notation:

implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
 implementation(kotlin("stdlib", kotlinVersion))

Annotation Processing

Kotlin supports annonation processing via the Kotlin annotation processing tool(kapt). Usage of kapt with Gradle is described on the kapt page.

Incremental Compilation

The Kotlin Gradle plugin supports incremental compilation. Incremental compilation tracks changes of source files between builds so only files affected by these changes would be compiled.

Incremental compilation is supported for Kotlin/JVM and Kotlin/JS projects. It's enabled by default since Kotlin 1.1.1 for Kotlin/JVM and 1.3.20 for Kotlin/JS.

There are several ways to override the default setting:

  • In Gradle configuration files: add the line kotlin.incremental=<value> for Kotlin/JVM or kotlin.incremental.js=<value> for Kotlin/JS projects either to gradle.properties or to local.properties file. <value> is a boolean value reflecting the usage of incremental compilation.

  • In Gradle command line parameters: add the parameter -Pkotlin.incremental or -Pkotlin.incremental.js with the boolean value reflecting the usage of incremental compilation. Note that in this case the parameter should be added to each subsequent build, and any build with disabled incremental compilation invalidates incremental caches.

Note that the first build isn't incremental in any case.

Gradle Build Cache Support (since 1.2.20)

The Kotlin plugin supports Gradle Build Cache (Gradle version 4.3 and above is required; caching is disabled with lower versions).

To disable the caching for all Kotlin tasks, set the system property flag kotlin.caching.enabled to false (run the build with the argument -Dkotlin.caching.enabled=false).

If you use kapt, note that the kapt annotation processing tasks are not cached by default. However, you can enable caching for them manually. See the kapt page for details.

Compiler Options

To specify additional compilation options, use the kotlinOptions property of a Kotlin compilation task.

When targeting the JVM, the tasks are called compileKotlin for production code and compileTestKotlin for test code. The tasks for custom source sets are called accordingly to the compile<Name>Kotlin pattern.

The names of the tasks in Android Projects contain the build variant names and follow the pattern compile<BuildVariant>Kotlin, for example, compileDebugKotlin, compileReleaseUnitTestKotlin.

When targeting JavaScript, the tasks are called compileKotlin2Js and compileTestKotlin2Js respectively, and compile<Name>Kotlin2Js for custom source sets.

To configure a single task, use its name. Examples:

compileKotlin {
    kotlinOptions.suppressWarnings = true
}

//or

compileKotlin {
    kotlinOptions {
        suppressWarnings = true
    }
}
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
// ...

val compileKotlin: KotlinCompile by tasks

compileKotlin.kotlinOptions.suppressWarnings = true

Note that with Gradle Kotlin DSL, you should get the task from the project's tasks first.

Use the types Kotlin2JsCompile and KotlinCompileCommon for the JS and Common targets, accordingly.

It is also possible to configure all Kotlin compilation tasks in the project:

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
    kotlinOptions { ... }
}
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

tasks.withType<KotlinCompile> {
    kotlinOptions.suppressWarnings = true
}

The complete list of options for the Gradle tasks is the following:

Attributes Common for JVM, JS, and JS DCE

Name Description Possible values Default value
allWarningsAsErrors Report an error if there are any warnings false
suppressWarnings Generate no warnings false
verbose Enable verbose logging output false
freeCompilerArgs A list of additional compiler arguments []

Attributes Common for JVM and JS

Name Description Possible values Default value
apiVersion Allow to use declarations only from the specified version of bundled libraries "1.0", "1.1", "1.2", "1.3", "1.4 (EXPERIMENTAL)"
languageVersion Provide source compatibility with specified language version "1.0", "1.1", "1.2", "1.3", "1.4 (EXPERIMENTAL)"

Attributes Specific for JVM

Name Description Possible values Default value
javaParameters Generate metadata for Java 1.8 reflection on method parameters false
jdkHome Path to JDK home directory to include into classpath, if differs from default JAVA_HOME
jvmTarget Target version of the generated JVM bytecode (1.6, 1.8, 9, 10, 11 or 12), default is 1.6 "1.6", "1.8", "9", "10", "11", "12" "1.6"
noJdk Don't include Java runtime into classpath false
noReflect Don't include Kotlin reflection implementation into classpath true
noStdlib Don't include Kotlin runtime into classpath true

Attributes Specific for JS

Name Description Possible values Default value
friendModulesDisabled Disable internal declaration export false
main Whether a main function should be called "call", "noCall" "call"
metaInfo Generate .meta.js and .kjsm files with metadata. Use to create a library true
moduleKind Kind of a module generated by compiler "plain", "amd", "commonjs", "umd" "plain"
noStdlib Don't use bundled Kotlin stdlib true
outputFile Output file path
sourceMap Generate source map false
sourceMapEmbedSources Embed source files into source map "never", "always", "inlining"
sourceMapPrefix Prefix for paths in a source map
target Generate JS files for specific ECMA version "v5" "v5"
typedArrays Translate primitive arrays to JS typed arrays true

Generating Documentation

To generate documentation for Kotlin projects, use Dokka; please refer to the Dokka README for configuration instructions. Dokka supports mixed-language projects and can generate output in multiple formats, including standard JavaDoc.

OSGi

For OSGi support see the Kotlin OSGi page.

Using Gradle Kotlin DSL

When using Gradle Kotlin DSL, apply the Kotlin plugins using the plugins { ... } block. If you apply them with apply { plugin(...) } instead, you may encounter unresolved references to the extensions generated by Gradle Kotlin DSL. To resolve that, you can comment out the erroneous usages, run the Gradle task kotlinDslAccessorsSnapshot, then uncomment the usages back and rerun the build or reimport the project into the IDE.

Examples

The following examples show different possibilities of configuring the Gradle plugin:

© 2010–2019 JetBrains s.r.o.
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/docs/reference/using-gradle.html