# Configure a Gradle project To build a Kotlin project with [Gradle](https://docs.gradle.org/current/userguide/userguide.html), you need to [add the Kotlin Gradle plugin](#apply-the-plugin) to your build script file `build.gradle(.kts)` and [configure the project's dependencies](#configure-dependencies) there. Note: To learn more about the contents of a build script, visit the [Explore the build script](get-started-with-jvm-gradle-project.html#explore-the-build-script) section. ## Apply the plugin To apply the Kotlin Gradle plugin, use the [plugins{} block](https://docs.gradle.org/current/userguide/plugins.html#sec:plugins_block) from the Gradle plugins DSL: Kotlin: ```KOTLIN plugins { // Replace `<...>` with the plugin name appropriate for your target environment kotlin("<...>") version "2.4.21" // For example, if your target environment is JVM: // kotlin("jvm") version "2.4.21" } ``` Groovy: ```GROOVY plugins { // Replace `<...>` with the plugin name appropriate for your target environment id 'org.jetbrains.kotlin.<...>' version '2.4.21' // For example, if your target environment is JVM: // id 'org.jetbrains.kotlin.jvm' version '2.4.21' } ``` Note: The Kotlin Gradle plugin (KGP) and Kotlin share the same version numbering. When configuring your project, check the Kotlin Gradle plugin (KGP) compatibility with available Gradle versions. In the following table, there are the minimum and maximum fully supported versions of Gradle and Android Gradle plugin (AGP): | KGP version |Gradle min and max versions |AGP min and max versions | ---------------------------------------------------------------------- | 2.4.20–2.4.21 |7.6.3–9.7.0 |8.5.2–9.3.1 | | 2.4.0–2.4.10 |7.6.3–9.5.0 |8.5.2–9.1.0 | | 2.3.20–2.3.21 |7.6.3–9.3.0 |8.2.2–9.0.0 | | 2.3.10 |7.6.3–9.0.0 |8.2.2–9.0.0 | | 2.3.0 |7.6.3–9.0.0 |8.2.2–8.13.0 | | 2.2.20–2.2.21 |7.6.3–8.14 |7.3.1–8.11.1 | | 2.2.0–2.2.10 |7.6.3–8.14 |7.3.1–8.10.0 | | 2.1.20–2.1.21 |7.6.3–8.12.1 |7.3.1–8.7.2 | | 2.1.0–2.1.10 |7.6.3–8.10* |7.3.1–8.7.2 | | 2.0.20–2.0.21 |6.8.3–8.8* |7.1.3–8.5 | | 2.0.0 |6.8.3–8.5 |7.1.3–8.3.1 | | 1.9.20–1.9.25 |6.8.3–8.1.1 |4.2.2–8.1.0 | Warning: *Kotlin 2.0.20–2.0.21 and Kotlin 2.1.0–2.1.10 are fully compatible with Gradle up to 8.6. Gradle versions 8.7–8.10 are also supported, with only one exception: If you use the Kotlin Multiplatform Gradle plugin, you may see deprecation warnings in your multiplatform projects calling the `withJava()` function in the JVM target. For more information, see [Java source sets created by default](https://kotlinlang.org/docs/multiplatform/multiplatform-compatibility-guide.html#java-source-sets-created-by-default). You can also use Gradle and AGP versions up to the latest releases, but if you do, keep in mind that you might encounter deprecation warnings or some new features might not work. For example, the Kotlin Gradle plugin and the `kotlin-multiplatform` plugin 2.4.21 require the minimum Gradle version of 7.6.3 for your project to compile. Similarly, the maximum fully supported version is 9.7.0. It doesn't have deprecated Gradle methods and properties, and supports all the current Gradle features. ### Earlier KGP versions | KGP version |Gradle min and max versions |AGP min and max versions | ---------------------------------------------------------------------- | 1.9.0–1.9.10 |6.8.3–7.6.0 |4.2.2–7.4.0 | | 1.8.20–1.8.22 |6.8.3–7.6.0 |4.1.3–7.4.0 | | 1.8.0–1.8.11 |6.8.3–7.3.3 |4.1.3–7.2.1 | | 1.7.20–1.7.22 |6.7.1–7.1.1 |3.6.4–7.0.4 | | 1.7.0–1.7.10 |6.7.1–7.0.2 |3.4.3–7.0.2 | | 1.6.20–1.6.21 |6.1.1–7.0.2 |3.4.3–7.0.2 | ### Kotlin Gradle plugin data in a project By default, the Kotlin Gradle plugin stores persistent project-specific data at the root of the project, in the `.kotlin` directory. Warning: Do not commit the `.kotlin` directory to version control. For example, if you are using Git, add `.kotlin` to your project's `.gitignore` file. There are properties you can add to the `gradle.properties` file of your project to configure this behavior: | Gradle property |Description | -------------------------------- | `kotlin.project.persistent.dir` |Configures the location where your project-level data is stored. Default: `/.kotlin` | | `kotlin.project.persistent.dir.gradle.disableWrite` |Controls whether writing Kotlin data to the `.gradle` directory is disabled (for backward compatibility with older IDEA versions). Default: false | ## Targeting the JVM To target the JVM, apply the Kotlin JVM plugin. Kotlin: ```KOTLIN plugins { kotlin("jvm") version "2.4.21" } ``` Groovy: ```GROOVY plugins { id "org.jetbrains.kotlin.jvm" version "2.4.21" } ``` The `version` should be literal in this block, and it cannot be applied from another build script. ### Kotlin and Java sources Kotlin sources and Java sources can be stored in the same directory, or they can be placed in different directories. The default convention is to use different directories: ```TEXT project - src - main (root) - kotlin - java ``` Warning: Do not store Java `.java` files in the `src/*/kotlin` directory, as the `.java` files will not be compiled. Instead, you can use `src/main/java`. The corresponding `sourceSets` property should be updated if you are not using the default convention: Kotlin: ```KOTLIN sourceSets.main { java.srcDirs("src/main/myJava", "src/main/myKotlin") } ``` Groovy: ```GROOVY sourceSets { main.kotlin.srcDirs += 'src/main/myKotlin' main.java.srcDirs += 'src/main/myJava' } ``` ### Check for JVM target compatibility of related compile tasks In the build module, you may have related compile tasks, for example: * `compileKotlin` and `compileJava` * `compileTestKotlin` and `compileTestJava` Note: `main` and `test` source set compile tasks are not related. For related tasks like these, the Kotlin Gradle plugin checks for JVM target compatibility. Different values of the [jvmTarget attribute](gradle-compiler-options.html#attributes-specific-to-jvm) in the `kotlin` extension or task and [targetCompatibility](https://docs.gradle.org/current/userguide/java_plugin.html#sec:java-extension) in the `java` extension or task cause JVM target incompatibility. For example: the `compileKotlin` task has `jvmTarget=1.8`, and the `compileJava` task has (or [inherits](https://docs.gradle.org/current/userguide/java_plugin.html#sec:java-extension)) `targetCompatibility=15`. Configure the behavior of this check for the whole project by setting the `kotlin.jvm.target.validation.mode` property in the `gradle.properties` file to: * `error` – the plugin fails the build; the default value for projects on Gradle 8.0+. * `warning` – the plugin prints a warning message; the default value for projects on Gradle less than 8.0. * `ignore` – the plugin skips the check and doesn't produce any messages. You can also configure it at task level in your `build.gradle(.kts)` file: Kotlin: ```KOTLIN tasks.withType().configureEach { jvmTargetValidationMode.set(org.jetbrains.kotlin.gradle.dsl.jvm.JvmTargetValidationMode.WARNING) } ``` Groovy: ```GROOVY tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile.class).configureEach { jvmTargetValidationMode = org.jetbrains.kotlin.gradle.dsl.jvm.JvmTargetValidationMode.WARNING } ``` To avoid JVM target incompatibility, [configure a toolchain](#gradle-java-toolchains-support) or align JVM versions manually. #### What can go wrong if targets are incompatible There are two ways of manually setting JVM targets for Kotlin and Java source sets: * The implicit way via [setting up a Java toolchain](#gradle-java-toolchains-support). * The explicit way via setting the `jvmTarget` attribute in the `kotlin` extension or task and `targetCompatibility` in the `java` extension or task. JVM target incompatibility occurs if you: * Explicitly set different values of `jvmTarget` and `targetCompatibility`. * Have a default configuration, and your JDK is not equal to `1.8`. Let's consider a default configuration of JVM targets when you have only the Kotlin JVM plugin in your build script and no additional settings for JVM targets: Kotlin: ```KOTLIN plugins { kotlin("jvm") version "2.4.21" } ``` Groovy: ```GROOVY plugins { id "org.jetbrains.kotlin.jvm" version "2.4.21" } ``` When there is no explicit information about the `jvmTarget` value in the build script, its default value is `null`, and the compiler translates it to the default value `1.8`. The `targetCompatibility` equals the current Gradle's JDK version, which is equal to your JDK version (unless you use a [Java toolchain approach](#gradle-java-toolchains-support)). Assuming that your JDK version is `17`, your published library artifact will [declare itself compatible](https://docs.gradle.org/current/userguide/publishing_gradle_module_metadata.html) with JDK 17+: `org.gradle.jvm.version=17`, which is wrong. In this case, you have to use Java 17 in your main project to add this library, even though the bytecode's version is `1.8`. [Configure a toolchain](#gradle-java-toolchains-support) to solve this issue. ### Gradle Java toolchains support Warning: A warning for Android users. To use Gradle toolchain support, use the Android Gradle plugin (AGP) version 8.1.0-alpha09 or higher. Gradle Java toolchain support [is available](https://issuetracker.google.com/issues/194113162) only from AGP 7.4.0. Nevertheless, because of [this issue](https://issuetracker.google.com/issues/260059413), AGP did not set `targetCompatibility` to be equal to the toolchain's JDK until the version 8.1.0-alpha09. If you use versions less than 8.1.0-alpha09, you need to configure `targetCompatibility` manually via `compileOptions`. Replace the placeholder `` with the JDK version you would like to use: ```KOTLIN android { compileOptions { sourceCompatibility = targetCompatibility = } } ``` Gradle 6.7 introduced [Java toolchains support](https://docs.gradle.org/current/userguide/toolchains.html). Using this feature, you can: * Use a JDK and a JRE that are different from the ones in Gradle to run compilations, tests, and executables. * Compile and test code with a not-yet-released language version. With toolchains support, Gradle can autodetect local JDKs and install missing JDKs that Gradle requires for the build. Now Gradle itself can run on any JDK and still reuse the [remote build cache feature](gradle-compilation-and-caches.html#gradle-build-cache-support) for tasks that depend on a major JDK version. The Kotlin Gradle plugin supports Java toolchains for Kotlin/JVM compilation tasks. JS and Native tasks don't use toolchains. The Kotlin compiler always runs on the JDK the Gradle daemon is running on. A Java toolchain: * Sets the [-jdk-home option](compiler-reference.html#jdk-home-path) available for JVM targets. * Sets the [compilerOptions.jvmTarget](gradle-compiler-options.html#attributes-specific-to-jvm) to the toolchain's JDK version if the user doesn't set the `jvmTarget` option explicitly. If the user doesn't configure the toolchain, the `jvmTarget` field uses the default value. Learn more about [JVM target compatibility](#check-for-jvm-target-compatibility-of-related-compile-tasks). * Sets the toolchain to be used by any Java compile, test, and javadoc tasks. * Affects which JDK [kapt workers](kapt.html#run-kapt-tasks-in-parallel) are running on. Use the following code to set a toolchain. Replace the placeholder `` with the JDK version you would like to use: Kotlin: ```KOTLIN kotlin { jvmToolchain { languageVersion.set(JavaLanguageVersion.of()) } // Or shorter: jvmToolchain() // For example: jvmToolchain(17) } ``` Groovy: ```GROOVY kotlin { jvmToolchain { languageVersion = JavaLanguageVersion.of() } // Or shorter: jvmToolchain() // For example: jvmToolchain(17) } ``` Note that setting a toolchain via the `kotlin` extension updates the toolchain for Java compile tasks as well. You can set a toolchain via the `java` extension, and Kotlin compilation tasks will use it: Kotlin: ```KOTLIN java { toolchain { languageVersion.set(JavaLanguageVersion.of()) } } ``` Groovy: ```GROOVY java { toolchain { languageVersion = JavaLanguageVersion.of() } } ``` If you use Gradle 8.0.2 or higher, you also need to add a [toolchain resolver plugin](https://docs.gradle.org/current/userguide/toolchains.html#sub:download_repositories). This type of plugin manages which repositories to download a toolchain from. As an example, add to your `settings.gradle(.kts)` the following plugin: Kotlin: ```KOTLIN plugins { id("org.gradle.toolchains.foojay-resolver-convention") version("1.0.0") } ``` Groovy: ```GROOVY plugins { id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0' } ``` Check that the version of `foojay-resolver-convention` corresponds to your Gradle version on the [Gradle site](https://docs.gradle.org/current/userguide/toolchains.html#sub:download_repositories). Note: To understand which toolchain Gradle uses, run your Gradle build with the [log level --info](https://docs.gradle.org/current/userguide/logging.html#sec:choosing_a_log_level) and find a string in the output starting with `[KOTLIN] Kotlin compilation 'jdkHome' argument:`. The part after the colon will be the JDK version from the toolchain. To set any JDK (even local) for a specific task, use the [Task DSL](#set-jdk-version-with-the-task-dsl). Learn more about [Gradle JVM toolchain support in the Kotlin plugin](https://blog.jetbrains.com/kotlin/2021/11/gradle-jvm-toolchain-support-in-the-kotlin-plugin/). ### Set JDK version with the Task DSL The Task DSL allows setting any JDK version for any task implementing the `UsesKotlinJavaToolchain` interface. At the moment, these tasks are `KotlinCompile` and `KaptTask`. If you want Gradle to search for the major JDK version, replace the `` placeholder in your build script: Kotlin: ```KOTLIN val service = project.extensions.getByType() val customLauncher = service.launcherFor { languageVersion.set(JavaLanguageVersion.of()) } project.tasks.withType().configureEach { kotlinJavaToolchain.toolchain.use(customLauncher) } ``` Groovy: ```GROOVY JavaToolchainService service = project.getExtensions().getByType(JavaToolchainService.class) Provider customLauncher = service.launcherFor { it.languageVersion = JavaLanguageVersion.of() } tasks.withType(UsesKotlinJavaToolchain::class).configureEach { task -> task.kotlinJavaToolchain.toolchain.use(customLauncher) } ``` Or you can specify the path to your local JDK and replace the placeholder `` with this JDK version: ```KOTLIN tasks.withType().configureEach { kotlinJavaToolchain.jdk.use( "/path/to/local/jdk", // Put a path to your JDK JavaVersion. // For example, JavaVersion.17 ) } ``` ### Associate compiler tasks You can associate compilations by setting up such a relationship between them that one compilation uses the compiled outputs of the other. Associating compilations establishes `internal` visibility between them. The Kotlin compiler associates some compilations by default, such as the `test` and `main` compilations of each target. If you need to express that one of your custom compilations is connected to another, create your own associated compilation. To make the IDE support associated compilations for inferring visibility between source sets, add the following code to your `build.gradle(.kts)`: Kotlin: ```KOTLIN val integrationTestCompilation = kotlin.target.compilations.create("integrationTest") { associateWith(kotlin.target.compilations.getByName("main")) } ``` Groovy: ```GROOVY integrationTestCompilation { kotlin.target.compilations.create("integrationTest") { associateWith(kotlin.target.compilations.getByName("main")) } } ``` Here, the `integrationTest` compilation is associated with the `main` compilation that gives access to `internal` objects from functional tests. ### Configure with Java Modules (JPMS) enabled To make the Kotlin Gradle plugin work with [Java Modules](https://dev.java/learn/modules/), add the following lines to your build script and replace `YOUR_MODULE_NAME` with a reference to your JPMS module, for example, `org.company.module`: Kotlin: ```KOTLIN tasks.named("compileJava", JavaCompile::class.java) { // Provide compiled Kotlin classes to javac – needed for Java/Kotlin mixed sources to work val mainOutput: FileCollection = sourceSets["main"].output options.compilerArgumentProviders.add(CommandLineArgumentProvider { listOf("--patch-module", "YOUR_MODULE_NAME=${mainOutput.asPath}") }) } ``` Groovy: ```GROOVY tasks.named("compileJava", JavaCompile.class) { // Provide compiled Kotlin classes to javac – needed for Java/Kotlin mixed sources to work FileCollection mainOutput = sourceSets["main"].output options.compilerArgumentProviders.add(new CommandLineArgumentProvider() { @Override Iterable asArguments() { return ["--patch-module", "YOUR_MODULE_NAME=${mainOutput.asPath}"] } }) } ``` Note: Put `module-info.java` into the `src/main/java` directory as usual. For a module, a package name in Kotlin files should be equal to the package name from `module-info.java` to avoid a "package is empty or does not exist" build failure. Learn more about: * [Building modules for the Java Module System](https://docs.gradle.org/current/userguide/java_library_plugin.html#sec:java_library_modular) * [Building applications using the Java Module System](https://docs.gradle.org/current/userguide/application_plugin.html#sec:application_modular) * [What "module" means in Kotlin](visibility-modifiers.html#modules) ### Other details #### Disable use of artifact in compilation task In some rare scenarios, you can experience a build failure caused by a circular dependency error. For example, when you have multiple compilations where one compilation can see all internal declarations of another, and the generated artifact relies on the output of both compilation tasks: ``` FAILURE: Build failed with an exception. What went wrong: Circular dependency between the following tasks: :lib:compileKotlinJvm --- :lib:jvmJar \--- :lib:compileKotlinJvm (*) (*) - details omitted (listed previously) ``` To fix this circular dependency error, we've added a Gradle property: `archivesTaskOutputAsFriendModule`. This property controls the use of artifact inputs in the compilation task and determines if a task dependency is created as a result. By default, this property is set to `true` to track the task dependency. If you encounter a circular dependency error, you can disable the use of the artifact in the compilation task to remove the task dependency and avoid the circular dependency error. To disable the use of the artifact in the compilation task, add the following to your `gradle.properties` file: ```KOTLIN kotlin.build.archivesTaskOutputAsFriendModule=false ``` #### Lazy Kotlin/JVM task creation Starting from Kotlin 1.8.20, the Kotlin Gradle plugin registers all tasks and doesn't configure them on a dry run. #### Non-default location of compile tasks' destinationDirectory If you override the Kotlin/JVM `KotlinJvmCompile`/`KotlinCompile` task's `destinationDirectory` location, update your build script. You need to explicitly add `sourceSets.main.kotlin.classesDirectories` to `sourceSets.main.outputs` in your JAR file: ```KOTLIN tasks.jar(type: Jar) { from sourceSets.main.outputs from sourceSets.main.kotlin.classesDirectories } ``` ## Targeting multiple platforms Projects targeting [multiple platforms](https://kotlinlang.org/docs/multiplatform/multiplatform-dsl-reference.html#targets), called [multiplatform projects](https://kotlinlang.org/docs/multiplatform/get-started.html), require the `kotlin-multiplatform` plugin. Note: The `kotlin-multiplatform` plugin works with Gradle 7.6.3 or later. Kotlin: ```KOTLIN plugins { kotlin("multiplatform") version "2.4.21" } ``` Groovy: ```GROOVY plugins { id 'org.jetbrains.kotlin.multiplatform' version '2.4.21' } ``` Learn more about [Kotlin Multiplatform for different platforms](https://kotlinlang.org/docs/multiplatform/get-started.html) and [Kotlin Multiplatform for iOS and Android](https://kotlinlang.org/docs/multiplatform/multiplatform-getting-started.html). ## Targeting Android It's recommended to use Android Studio for creating Android applications. [Learn how to use the Android Gradle plugin](https://developer.android.com/studio/releases/gradle-plugin). ## Targeting the web Kotlin, through Kotlin Multiplatform, offers two approaches for web development: * JavaScript-based (using the Kotlin/JS compiler) * WebAssembly-based (using the Kotlin/Wasm compiler) Both approaches use the Kotlin Multiplatform plugin but support different use cases. The sections below explain how to configure each target in your Gradle build and when to use them. ### Targeting JavaScript Use Kotlin/JS if your goal is to: * Share business logic with a JavaScript/TypeScript codebase * Build non-shareable web apps with Kotlin For more information, see [Web development](web-overview.html#kotlin-js). When targeting JavaScript, use the `kotlin-multiplatform` plugin: Kotlin: ```KOTLIN plugins { kotlin("multiplatform") version "2.4.21" } ``` Groovy: ```GROOVY plugins { id 'org.jetbrains.kotlin.multiplatform' version '2.4.21' } ``` Configure the JavaScript target by specifying whether it should run in the browser or the Node.js environment: ```KOTLIN kotlin { js().browser { // or js().nodejs /* ... */ } } ``` Note: See [further details about the Gradle configuration for JavaScript](https://kotlinlang.org/docs/multiplatform/multiplatform-dsl-reference.html#web-targets) and learn more about [setting up a Kotlin/JS project](js-project-setup.html). ### Targeting WebAssembly Use Kotlin/Wasm if you want to share both logic and UI across multiple platforms. For more information, see [Web development](web-overview.html#kotlin-wasm). As with JavaScript, use the `kotlin-multiplatform` plugin when targeting WebAssembly (Wasm): Kotlin: ```KOTLIN plugins { kotlin("multiplatform") version "2.4.21" } ``` Groovy: ```GROOVY plugins { id 'org.jetbrains.kotlin.multiplatform' version '2.4.21' } ``` Depending on your requirements, you can target: * `wasmJs`: for running in browsers or Node.js * `wasmWasi`: for running in Wasm environments supporting [WASI (WebAssembly System Interface)](https://wasi.dev/), such as Wasmtime, WasmEdge, and so on. Configure the `wasmJs` target for web browsers or Node.js: ```KOTLIN kotlin { wasmJs { browser { // or nodejs /* ... */ } } } ``` For WASI environments, configure the `wasmWasi` target with Node.js or Wasmtime: ```KOTLIN kotlin { wasmWasi { nodejs { // or wasmtime /* ... */ } } } ``` Note: [See further details about the Gradle configuration for Wasm](https://kotlinlang.org/docs/multiplatform/multiplatform-dsl-reference.html#web-targets). ### Kotlin and Java sources for the web target The KGP only works for Kotlin files, so it is recommended that you keep Kotlin and Java files separate (if the project contains Java files). If you don't store them separately, specify the source folder in the `sourceSets{}` block: Kotlin: ```KOTLIN kotlin { sourceSets["main"].apply { kotlin.srcDir("src/main/myKotlin") } } ``` Groovy: ```GROOVY kotlin { sourceSets { main.kotlin.srcDirs += 'src/main/myKotlin' } } ``` ## Triggering configuration actions with the KotlinBasePlugin interface To trigger some configuration action whenever any Kotlin Gradle plugin (JVM, JS, Multiplatform, Native, and others) is applied, use the `KotlinBasePlugin` interface that all Kotlin plugins inherit from: Kotlin: ```KOTLIN import org.jetbrains.kotlin.gradle.plugin.KotlinBasePlugin // ... project.plugins.withType() { // Configure your action here } ``` Groovy: ```GROOVY import org.jetbrains.kotlin.gradle.plugin.KotlinBasePlugin // ... project.plugins.withType(KotlinBasePlugin.class) { // Configure your action here } ``` ## Configure dependencies To add a dependency on a library, set the dependency of the required [type](#dependency-types) (for example, `implementation`) in the `dependencies{}` block of the source sets DSL. Kotlin: ```KOTLIN kotlin { sourceSets { commonMain.dependencies { implementation("com.example:my-library:1.0") } } } ``` Groovy: ```GROOVY kotlin { sourceSets { commonMain { dependencies { implementation 'com.example:my-library:1.0' } } } } ``` ### Configure dependencies at the top level You can configure common dependencies in multiplatform projects using a top-level `dependencies {}` block. Dependencies declared here behave as if they were added to the `commonMain` or `commonTest` source sets. To use the top-level `dependencies {}` block, opt in by adding the `@OptIn(ExperimentalKotlinGradlePluginApi::class)` annotation before the block: Kotlin: ```KOTLIN kotlin { @OptIn(ExperimentalKotlinGradlePluginApi::class) dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0") } } ``` Groovy: ```GROOVY kotlin { dependencies { implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0' } } ``` Add platform-specific dependencies inside the `sourceSets {}` block of the corresponding target. You can share your feedback on this feature in [YouTrack](https://youtrack.jetbrains.com/issue/KT-76446). ### Dependency types Choose the dependency type based on your requirements. | Type |Description |When to use | ---------------------------------- | `api` |Used both during compilation and at runtime and is exported to library consumers. |If any type from a dependency is used in the public API of the current module, use an `api` dependency. | | `implementation` |Used during compilation and at runtime for the current module, but is not exposed for compilation of other modules depending on the one with the `implementation` dependency. | Use for dependencies needed for the internal logic of a module. If a module is an endpoint application which is not published, use `implementation` dependencies instead of `api` dependencies. | | `compileOnly` |Used for compilation of the current module and is not available at runtime nor during compilation of other modules. |Use for APIs which have a third-party implementation available at runtime. | | `runtimeOnly` |Available at runtime but is not visible during compilation of any module. | | ### Dependency on the standard library A dependency on the standard library (`stdlib`) is added automatically to each source set. The version of the standard library used is the same as the version of the Kotlin Gradle plugin. For platform-specific source sets, the corresponding platform-specific variant of the library is used, while a common standard library is added to the rest. The Kotlin Gradle plugin selects the appropriate JVM standard library depending on the `compilerOptions.jvmTarget` [compiler option](gradle-compiler-options.html) of your Gradle build script. If you declare a standard library dependency explicitly (for example, if you need a different version), the Kotlin Gradle plugin won't override it or add a second standard library. If you don't need a standard library at all, you can add the following Gradle property to your `gradle.properties` file: ``` kotlin.stdlib.default.dependency=false ``` #### Versions alignment of transitive dependencies From Kotlin standard library version 1.9.20, Gradle uses metadata included in the standard library to automatically align transitive `kotlin-stdlib-jdk7` and `kotlin-stdlib-jdk8` dependencies. If you add a dependency for any Kotlin standard library version between 1.8.0 – 1.9.10, for example: `implementation("org.jetbrains.kotlin:kotlin-stdlib:1.8.0")`, then the Kotlin Gradle Plugin uses this Kotlin version for transitive `kotlin-stdlib-jdk7` and `kotlin-stdlib-jdk8` dependencies. This avoids class duplication from different standard library versions. [Learn more about merging kotlin-stdlib-jdk7 and kotlin-stdlib-jdk8 into kotlin-stdlib](whatsnew18.html#updated-jvm-compilation-target). You can disable this behavior with the `kotlin.stdlib.jdk.variants.version.alignment` Gradle property in your `gradle.properties` file: ``` kotlin.stdlib.jdk.variants.version.alignment=false ``` ##### Other ways to align versions * If you have issues with version alignment, you can align all versions via the Kotlin [BOM](https://docs.gradle.org/current/userguide/platforms.html#sub:bom_import). Declare a platform dependency on `kotlin-bom` in your build script: Kotlin: ```KOTLIN implementation(platform("org.jetbrains.kotlin:kotlin-bom:2.4.21")) ``` Groovy: ```GROOVY implementation platform('org.jetbrains.kotlin:kotlin-bom:2.4.21') ``` * If you don't add a dependency for a standard library version, but you have two different dependencies that transitively bring different old versions of the Kotlin standard library, then you can explicitly require `2.4.21` versions of these transitive libraries: Kotlin: ```KOTLIN dependencies { constraints { add("implementation", "org.jetbrains.kotlin:kotlin-stdlib-jdk7") { version { require("2.4.21") } } add("implementation", "org.jetbrains.kotlin:kotlin-stdlib-jdk8") { version { require("2.4.21") } } } } ``` Groovy: ```GROOVY dependencies { constraints { add("implementation", "org.jetbrains.kotlin:kotlin-stdlib-jdk7") { version { require("2.4.21") } } add("implementation", "org.jetbrains.kotlin:kotlin-stdlib-jdk8") { version { require("2.4.21") } } } } ``` * If you add a dependency for Kotlin standard library version `2.4.21`: `implementation("org.jetbrains.kotlin:kotlin-stdlib:2.4.21")`, and an old version (earlier than `1.8.0`) of the Kotlin Gradle plugin, update the Kotlin Gradle plugin to match the standard library version: Kotlin: ```KOTLIN plugins { // replace `<...>` with the plugin name kotlin("<...>") version "2.4.21" } ``` Groovy: ```GROOVY plugins { // replace `<...>` with the plugin name id "org.jetbrains.kotlin.<...>" version "2.4.21" } ``` * If you use versions prior to `1.8.0` of `kotlin-stdlib-jdk7`/`kotlin-stdlib-jdk8`, for example, `implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:SOME_OLD_KOTLIN_VERSION")`, and a dependency that transitively brings `kotlin-stdlib:1.8+`, [replace your kotlin-stdlib-jdk<7/8>:SOME_OLD_KOTLIN_VERSION with kotlin-stdlib-jdk*:2.4.21](whatsnew18.html#updated-jvm-compilation-target) or [exclude](https://docs.gradle.org/current/userguide/dependency_downgrade_and_exclude.html#sec:excluding-transitive-deps) the transitive `kotlin-stdlib:1.8+` from the library that brings it: Kotlin: ```KOTLIN dependencies { implementation("com.example:lib:1.0") { exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib") } } ``` Groovy: ```GROOVY dependencies { implementation("com.example:lib:1.0") { exclude group: "org.jetbrains.kotlin", module: "kotlin-stdlib" } } ``` ### Set dependencies on test libraries The [kotlin.test](https://kotlinlang.org/api/latest/kotlin.test/) API is available for testing Kotlin projects on all supported platforms. Add the `kotlin-test` dependency to the `commonTest` source set, so that the Gradle plugin can infer the corresponding test dependencies for each test source set. Kotlin/Native targets do not require additional test dependencies, and the `kotlin.test` API implementations are built-in. Kotlin: ```KOTLIN kotlin { sourceSets { commonTest.dependencies { implementation(kotlin("test")) // This brings all the platform dependencies automatically } } } ``` Groovy: ```GROOVY kotlin { sourceSets { commonTest { dependencies { implementation kotlin("test") // This brings all the platform dependencies automatically } } } } ``` Note: You can use shorthand for a dependency on a Kotlin module, for example, kotlin("test") for "org.jetbrains.kotlin:kotlin-test". You can use the `kotlin-test` dependency in any shared or platform-specific source set as well. #### JVM variants of kotlin-test For Kotlin/JVM, Gradle uses JUnit 4 by default. Therefore, the `kotlin("test")` dependency resolves to the variant for JUnit 4, namely `kotlin-test-junit`. You can choose JUnit 5 or TestNG by calling [useJUnitPlatform()](https://docs.gradle.org/current/javadoc/org/gradle/api/tasks/testing/Test.html#useJUnitPlatform) or [useTestNG()](https://docs.gradle.org/current/javadoc/org/gradle/api/tasks/testing/Test.html#useTestNG) in the test task of your build script. The following example is for a Kotlin Multiplatform project: Kotlin: ```KOTLIN kotlin { jvm { testRuns["test"].executionTask.configure { useJUnitPlatform() } } sourceSets { commonTest.dependencies { implementation(kotlin("test")) } } } ``` Groovy: ```GROOVY kotlin { jvm { testRuns["test"].executionTask.configure { useJUnitPlatform() } } sourceSets { commonTest { dependencies { implementation kotlin("test") } } } } ``` The following example is for a JVM project: Kotlin: ```KOTLIN dependencies { testImplementation(kotlin("test")) } tasks { test { useTestNG() } } ``` Groovy: ```GROOVY dependencies { testImplementation 'org.jetbrains.kotlin:kotlin-test' } test { useTestNG() } ``` [Learn how to test code using JUnit on the JVM](jvm-test-using-junit.html). Automatic JVM variant resolution can sometimes cause problems for your configuration. In that case, you can specify the necessary framework explicitly and disable the automatic resolution by adding this line to the project `gradle.properties` file: ```TEXT kotlin.test.infer.jvm.variant=false ``` If you have used a variant of `kotlin("test")` in your build script explicitly and your project build stopped working with a compatibility conflict, see [this issue in the Compatibility guide](compatibility-guide-15.html#do-not-mix-several-jvm-variants-of-kotlin-test-in-a-single-project). ### Set a dependency on a kotlinx library If you use a multiplatform library and need to depend on the shared code, set the dependency only once in the shared source set. Use the library's base artifact name, such as `kotlinx-coroutines-core` or `ktor-client-core`: Kotlin: ```KOTLIN kotlin { sourceSets { commonMain.dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0") } } } ``` Groovy: ```GROOVY kotlin { sourceSets { commonMain { dependencies { implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0' } } } } ``` If you need a kotlinx library for a platform-specific dependency, you can still use the library's base artifact name in the corresponding platform source set: Kotlin: ```KOTLIN kotlin { sourceSets { jvmMain.dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0") } } } ``` Groovy: ```GROOVY kotlin { sourceSets { jvmMain { dependencies { implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0' } } } } ``` ## Declare repositories You can declare a publicly-available repository to use its open source dependencies. In the `repositories{}` block, set the name of the repository: Kotlin: ```KOTLIN repositories { mavenCentral() } ``` Groovy: ```GROOVY repositories { mavenCentral() } ``` Popular repositories are [Maven Central](https://central.sonatype.com/) and [Google's Maven repository](https://maven.google.com/web/index.html). Warning: If you also work with Maven projects, we recommend avoiding adding `mavenLocal()` as a repository because you may experience problems when switching between Gradle and Maven projects. If you must add the `mavenLocal()` repository, add it as the last repository in your `repositories{}` block. For more information, see [The case for mavenLocal()](https://docs.gradle.org/current/userguide/declaring_repositories.html#sec:case-for-maven-local). If you need to declare the same repositories in more than one subproject, declare the repositories centrally in the `dependencyResolutionManagement{}` block in your `settings.gradle(.kts)` file: Kotlin: ```KOTLIN dependencyResolutionManagement { repositories { mavenCentral() } } ``` Groovy: ```KOTLIN dependencyResolutionManagement { repositories { mavenCentral() } } ``` Any declared repositories in subprojects override repositories declared centrally. For more information on how to control this behavior and what options are available, see [Gradle's documentation](https://docs.gradle.org/current/userguide/declaring_repositories.html#sub:centralized-repository-declaration). ## Register generated sources Register generated sources to help IDEs, third-party plugins, and other tools distinguish between generated code and regular source files. This helps tools like IDEs highlight generated code differently in the UI and trigger generation tasks when importing the project. Use the [KotlinSourceSet](https://kotlinlang.org/api/kotlin-gradle-plugin/kotlin-gradle-plugin-api/org.jetbrains.kotlin.gradle.plugin/-kotlin-source-set/) interface to register generated sources. To register a directory that contains Kotlin files, use the [generatedKotlin](https://kotlinlang.org/api/kotlin-gradle-plugin/kotlin-gradle-plugin-api/org.jetbrains.kotlin.gradle.plugin/-kotlin-source-set/generated-kotlin.html) property with the [SourceDirectorySet](https://docs.gradle.org/current/kotlin-dsl/gradle/org.gradle.api.file/-source-directory-set/index.html) type in your `build.gradle.kts` file. For example: ```KOTLIN val generatorTask = project.tasks.register("generator") { val outputDirectory = project.layout.projectDirectory.dir("src/main/kotlinGen") outputs.dir(outputDirectory) doLast { outputDirectory.file("generated.kt").asFile.writeText( // language=kotlin """ fun printHello() { println("hello") } """.trimIndent() ) } } kotlin.sourceSets.getByName("main").generatedKotlin.srcDir(generatorTask) ``` This example creates a new task `generator` with an output directory of `"src/main/kotlinGen"`. When the task runs, the `doLast {}` task action creates a `generated.kt` file in the output directory. Finally, the example registers the task's output as a generated source. If you're developing a Gradle plugin, you can use the [allKotlinSources](https://kotlinlang.org/api/kotlin-gradle-plugin/kotlin-gradle-plugin-api/org.jetbrains.kotlin.gradle.plugin/-kotlin-source-set/all-kotlin-sources.html) property to access all sources registered in the [KotlinSourceSet.kotlin](https://kotlinlang.org/api/kotlin-gradle-plugin/kotlin-gradle-plugin-api/org.jetbrains.kotlin.gradle.plugin/-kotlin-source-set/kotlin.html) and `KotlinSourceSet.generatedKotlin` properties. ## What's next? Learn more about: * [Compiler options and how to pass them](gradle-compiler-options.html). * [Incremental compilation, caches support, build reports, and the Kotlin daemon](gradle-compilation-and-caches.html). * [Gradle basics and specifics](https://docs.gradle.org/current/userguide/userguide.html). * [Support for Gradle plugin variants](gradle-plugin-variants.html).