配置 Gradle 项目

To build a Kotlin project with Gradle, you need to add the Kotlin Gradle plugin to your build script file build.gradle(.kts) and configure the project’s dependencies there.

To learn more about the contents of a build script, visit the Explore the build script section.

配置 Gradle 项目 - 图1

Apply the plugin

To apply the Kotlin Gradle plugin, use the plugins block from the Gradle plugins DSL:

【Kotlin】

  1. // replace `<……>` with the plugin name
  2. plugins {
  3. kotlin("<……>") version "1.9.10"
  4. }

【Groovy】

  1. // replace `<……>` with the plugin name
  2. plugins {
  3. id 'org.jetbrains.kotlin.<……>' version '1.9.10'
  4. }

The Kotlin Gradle plugin (KGP) and Kotlin share the same version numbering.

配置 Gradle 项目 - 图2

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 versionGradle min and max versionsAGP min and max versions
1.9.06.8.3 – 7.6.04.2.2 – 7.4.0
1.8.206.8.3 – 7.6.04.1.3 – 7.4.0
1.8.06.8.3 – 7.3.34.1.3 – 7.2.1
1.7.206.7.1 – 7.1.13.6.4 – 7.0.4
1.7.06.7.1 – 7.0.23.4.3 – 7.0.2
1.6.206.1.1 - 7.0.23.4.3 - 7.0.2

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.

配置 Gradle 项目 - 图3

For example, the Kotlin Gradle plugin and the kotlin-multiplatform plugin 1.9.10 require the minimum Gradle version of 6.8.3 for your project to compile.

Similarly, the maximum fully supported version is 7.6.0. It doesn’t have deprecated Gradle methods and properties, and supports all the current Gradle features.

面向 JVM

如需面向 JVM 平台,请应用 Kotlin JVM 插件。

【Kotlin】

  1. plugins {
  2. kotlin("jvm") version "1.9.10"
  3. }

【Groovy】

  1. plugins {
  2. id "org.jetbrains.kotlin.jvm" version "1.9.10"
  3. }

在这个代码块中的 version 应该是字面值,并且不能在其他构建脚本中应用。

Kotlin and Java sources

Kotlin 源代码可以与 Java 源代码放在相同目录或者不同目录中。

默认约定是使用不同的目录:

  1. project
  2. - src
  3. - main (root)
  4. - kotlin
  5. - java

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.

配置 Gradle 项目 - 图4

如果不使用默认约定,那么应该更新相应的 sourceSets 属性:

【Kotlin】

  1. sourceSets.main {
  2. java.srcDirs("src/main/myJava", "src/main/myKotlin")
  3. }

【Groovy】

  1. sourceSets {
  2. main.kotlin.srcDirs += 'src/main/myKotlin'
  3. main.java.srcDirs += 'src/main/myJava'
  4. }

In the build module, you may have related compile tasks, for example:

  • compileKotlin and compileJava
  • compileTestKotlin and compileTestJava

main and test source set compile tasks are not related.

配置 Gradle 项目 - 图5

For related tasks like these, the Kotlin Gradle plugin checks for JVM target compatibility. Different values of the jvmTarget attribute in the kotlin extension or task and targetCompatibility 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) targetCompatibility=15.

Configure the behavior of this check for the whole project by setting the kotlin.jvm.target.validation.mode property in the build.gradle(.kts) 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】

  1. tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile>().configureEach {
  2. jvmTargetValidationMode.set(org.jetbrains.kotlin.gradle.dsl.jvm.JvmTargetValidationMode.WARNING)
  3. }

【Groovy】

  1. tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile.class).configureEach {
  2. jvmTargetValidationMode = org.jetbrains.kotlin.gradle.dsl.jvm.JvmTargetValidationMode.WARNING
  3. }

To avoid JVM target incompatibility, configure a toolchain or align JVM versions manually.

What can go wrong if not checking targets compatibility

There are two ways of manually setting JVM targets for Kotlin and Java source sets:

  • The implicit way via setting up a Java toolchain.
  • 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】

  1. plugins {
  2. kotlin("jvm") version "1.9.10"
  3. }

【Groovy】

  1. plugins {
  2. id "org.jetbrains.kotlin.jvm" version "1.9.10"
  3. }

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). Assuming that your JDK version is 17, your published library artifact will declare itself compatible 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 to solve this issue.

Gradle Java toolchains support

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 only from AGP 7.4.0. Nevertheless, because of this issue, 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 <MAJOR_JDK_VERSION> with the JDK version you would like to use:

  1. android {
  2. compileOptions {
  3. sourceCompatibility = <MAJOR_JDK_VERSION>
  4. targetCompatibility = <MAJOR_JDK_VERSION>
  5. }
  6. }

配置 Gradle 项目 - 图6

Gradle 6.7 introduced Java toolchains support. 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 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 available for JVM targets.
  • Sets the compilerOptions.jvmTarget 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.
  • Sets the toolchain to be used by any Java compile, test and javadoc tasks.
  • Affects which JDK kapt workers are running on.

Use the following code to set a toolchain. Replace the placeholder <MAJOR_JDK_VERSION> with the JDK version you would like to use:

【Kotlin】

  1. kotlin {
  2. jvmToolchain {
  3. languageVersion.set(JavaLanguageVersion.of(<MAJOR_JDK_VERSION>))
  4. }
  5. // Or shorter:
  6. jvmToolchain(<MAJOR_JDK_VERSION>)
  7. // For example:
  8. jvmToolchain(17)
  9. }

【Groovy】

  1. kotlin {
  2. jvmToolchain {
  3. languageVersion.set(JavaLanguageVersion.of(<MAJOR_JDK_VERSION>))
  4. }
  5. // Or shorter:
  6. jvmToolchain(<MAJOR_JDK_VERSION>)
  7. // For example:
  8. jvmToolchain(17)
  9. }

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】

  1. java {
  2. toolchain {
  3. languageVersion.set(JavaLanguageVersion.of(<MAJOR_JDK_VERSION>))
  4. }
  5. }

【Groovy】

  1. java {
  2. toolchain {
  3. languageVersion.set(JavaLanguageVersion.of(<MAJOR_JDK_VERSION>))
  4. }
  5. }

If you use Gradle 8.0.2 or higher, you also need to add a toolchain resolver plugin. 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】

  1. plugins {
  2. id("org.gradle.toolchains.foojay-resolver-convention") version("0.5.0")
  3. }

【Groovy】

  1. plugins {
  2. id 'org.gradle.toolchains.foojay-resolver-convention' version '0.5.0'
  3. }

Check that the version of foojay-resolver-convention corresponds to your Gradle version on the Gradle site.

To understand which toolchain Gradle uses, run your Gradle build with the log level —info 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.

配置 Gradle 项目 - 图7

To set any JDK (even local) for a specific task, use the Task DSL.

Learn more about 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 <MAJOR_JDK_VERSION> placeholder in your build script:

【Kotlin】

  1. val service = project.extensions.getByType<JavaToolchainService>()
  2. val customLauncher = service.launcherFor {
  3. languageVersion.set(JavaLanguageVersion.of(<MAJOR_JDK_VERSION>))
  4. }
  5. project.tasks.withType<UsesKotlinJavaToolchain>().configureEach {
  6. kotlinJavaToolchain.toolchain.use(customLauncher)
  7. }

【Groovy】

  1. JavaToolchainService service = project.getExtensions().getByType(JavaToolchainService.class)
  2. Provider<JavaLauncher> customLauncher = service.launcherFor {
  3. it.languageVersion.set(JavaLanguageVersion.of(<MAJOR_JDK_VERSION>))
  4. }
  5. tasks.withType(UsesKotlinJavaToolchain::class).configureEach { task ->
  6. task.kotlinJavaToolchain.toolchain.use(customLauncher)
  7. }

Or you can specify the path to your local JDK and replace the placeholder <LOCAL_JDK_VERSION> with this JDK version:

  1. tasks.withType<UsesKotlinJavaToolchain>().configureEach {
  2. kotlinJavaToolchain.jdk.use(
  3. "/path/to/local/jdk", // Put a path to your JDK
  4. JavaVersion.<LOCAL_JDK_VERSION> // For example, JavaVersion.17
  5. )
  6. }

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】

  1. val integrationTestCompilation = kotlin.target.compilations.create("integrationTest") {
  2. associateWith(kotlin.target.compilations.getByName("main"))
  3. }

【Groovy】

  1. integrationTestCompilation {
  2. kotlin.target.compilations.create("integrationTest") {
  3. associateWith(kotlin.target.compilations.getByName("main"))
  4. }
  5. }

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, 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】

  1. // Add the following three lines if you use a Gradle version less than 7.0
  2. java {
  3. modularity.inferModulePath.set(true)
  4. }
  5. tasks.named("compileJava", JavaCompile::class.java) {
  6. options.compilerArgumentProviders.add(CommandLineArgumentProvider {
  7. // Provide compiled Kotlin classes to javac – needed for Java/Kotlin mixed sources to work
  8. listOf("--patch-module", "YOUR_MODULE_NAME=${sourceSets["main"].output.asPath}")
  9. })
  10. }

【Groovy】

  1. // Add the following three lines if you use a Gradle version less than 7.0
  2. java {
  3. modularity.inferModulePath = true
  4. }
  5. tasks.named("compileJava", JavaCompile.class) {
  6. options.compilerArgumentProviders.add(new CommandLineArgumentProvider() {
  7. @Override
  8. Iterable<String> asArguments() {
  9. // Provide compiled Kotlin classes to javac – needed for Java/Kotlin mixed sources to work
  10. return ["--patch-module", "YOUR_MODULE_NAME=${sourceSets["main"].output.asPath}"]
  11. }
  12. })
  13. }

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.

配置 Gradle 项目 - 图8

Learn more about:

Other details

Learn more about Kotlin/JVM.

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.

编译任务的 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:

  1. tasks.jar(type: Jar) {
  2. from sourceSets.main.outputs
  3. from sourceSets.main.kotlin.classesDirectories
  4. }

Targeting multiple platforms

Projects targeting multiple platforms, called multiplatform projects, require the kotlin-multiplatform plugin. Learn more about the plugin.

The kotlin-multiplatform plugin works with Gradle 6.8.3 or later.

配置 Gradle 项目 - 图9

【Kotlin】

  1. plugins {
  2. kotlin("multiplatform") version "1.9.10"
  3. }

【Groovy】

  1. plugins {
  2. id 'org.jetbrains.kotlin.multiplatform' version '1.9.10'
  3. }

Learn more about Kotlin Multiplatform for different platforms and Kotlin Multiplatform for iOS and Android.

面向 Android

It’s recommended to use Android Studio for creating Android applications. Learn how to use the Android Gradle plugin.

Targeting JavaScript

When targeting JavaScript, use the kotlin-multiplatform plugin as well. Learn more about setting up a Kotlin/JS project

【Kotlin】

  1. plugins {
  2. kotlin("multiplatform") version "1.9.10"
  3. }

【Groovy】

  1. plugins {
  2. id 'org.jetbrains.kotlin.multiplatform' version '1.9.10'
  3. }

Kotlin and Java sources for JavaScript

这个插件只适用于 Kotlin 文件,因此建议将 Kotlin 和 Java 文件分开(当同一项目包含 Java 文件时)。 If you don’t store them separately , specify the source folder in the sourceSets block:

【Kotlin】

  1. kotlin {
  2. sourceSets["main"].apply {
  3. kotlin.srcDir("src/main/myKotlin")
  4. }
  5. }

【Groovy】

  1. kotlin {
  2. sourceSets {
  3. main.kotlin.srcDirs += 'src/main/myKotlin'
  4. }
  5. }

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】

  1. import org.jetbrains.kotlin.gradle.plugin.KotlinBasePlugin
  2. // ...
  3. project.plugins.withType<KotlinBasePlugin>() {
  4. // Configure your action here
  5. }

【Groovy】

  1. import org.jetbrains.kotlin.gradle.plugin.KotlinBasePlugin
  2. // ...
  3. project.plugins.withType(KotlinBasePlugin.class) {
  4. // Configure your action here
  5. }

Configure dependencies

To add a dependency on a library, set the dependency of the required type (for example, implementation) in the dependencies block of the source sets DSL.

【Kotlin】

  1. kotlin {
  2. sourceSets {
  3. val commonMain by getting {
  4. dependencies {
  5. implementation("com.example:my-library:1.0")
  6. }
  7. }
  8. }
  9. }

【Groovy】

  1. kotlin {
  2. sourceSets {
  3. commonMain {
  4. dependencies {
  5. implementation 'com.example:my-library:1.0'
  6. }
  7. }
  8. }
  9. }

Alternatively, you can set dependencies at top level.

Dependency types

Choose the dependency type based on your requirements.

TypeDescriptionWhen to use
apiUsed 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.
implementationUsed 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.

compileOnlyUsed 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.
runtimeOnlyAvailable at runtime but is not visible during compilation of any module.

对标准库的依赖

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 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 do not need a standard library at all, you can add the opt-out option to the gradle.properties:

  1. kotlin.stdlib.default.dependency=false

Versions alignment of transitive dependencies

If you explicitly write the Kotlin version 1.8.0 or higher in your dependencies, 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 is for avoiding class duplication from different stdlib versions. Learn more about merging kotlin-stdlib-jdk7 and kotlin-stdlib-jdk8 into kotlin-stdlib. You can disable this behavior with the kotlin.stdlib.jdk.variants.version.alignment Gradle property:

  1. kotlin.stdlib.jdk.variants.version.alignment=false
Other ways to align versions
  • In case you have issues with versions alignment, align all versions via the Kotlin BOM. Declare a platform dependency on kotlin-bom in your build script:

【Kotlin】

  1. implementation(platform("org.jetbrains.kotlin:kotlin-bom:1.9.10"))

【Groovy】

  1. implementation platform('org.jetbrains.kotlin:kotlin-bom:1.9.10')
  • If you don’t have a standard library explicitly: kotlin.stdlib.default.dependency=false in your gradle.properties, but one of your dependencies transitively brings some old Kotlin stdlib version, for example, kotlin-stdlib-jdk7:1.7.20 and another dependency transitively brings kotlin-stdlib:1.8+ – in this case, you can require 1.9.10 versions of these transitive libraries:

【Kotlin】

  1. dependencies {
  2. constraints {
  3. add("implementation", "org.jetbrains.kotlin:kotlin-stdlib-jdk7") {
  4. version {
  5. require("1.9.10")
  6. }
  7. }
  8. add("implementation", "org.jetbrains.kotlin:kotlin-stdlib-jdk8") {
  9. version {
  10. require("1.9.10")
  11. }
  12. }
  13. }
  14. }

【Groovy】

  1. dependencies {
  2. constraints {
  3. add("implementation", "org.jetbrains.kotlin:kotlin-stdlib-jdk7") {
  4. version {
  5. require("1.9.10")
  6. }
  7. }
  8. add("implementation", "org.jetbrains.kotlin:kotlin-stdlib-jdk8") {
  9. version {
  10. require("1.9.10")
  11. }
  12. }
  13. }
  14. }
  • If you have a Kotlin version equal to 1.9.10: implementation("org.jetbrains.kotlin:kotlin-stdlib:1.9.10") and an old version (less than 1.8.0) of a Kotlin Gradle plugin – update the Kotlin Gradle plugin:

【Kotlin】

  1. plugins {
  2. // replace `<...>` with the plugin name
  3. kotlin("<...>") version "1.9.10"
  4. }

【Groovy】

  1. plugins {
  2. // replace `<...>` with the plugin name
  3. id "org.jetbrains.kotlin.<...>" version "1.9.10"
  4. }

【Kotlin】

  1. dependencies {
  2. implementation("com.example:lib:1.0") {
  3. exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib")
  4. }
  5. }

【Groovy】

  1. dependencies {
  2. implementation("com.example:lib:1.0") {
  3. exclude group: "org.jetbrains.kotlin", module: "kotlin-stdlib"
  4. }
  5. }

Set dependencies on test libraries

The kotlin.test API is available for testing Kotlin projects on all supported platforms. Add the dependency kotlin-test to the commonTest source set, so that the Gradle plugin can infer the corresponding test dependencies for each test source set:

  • kotlin-test-common and kotlin-test-annotations-common for common source sets
  • kotlin-test-junit for JVM source sets
  • kotlin-test-js for Kotlin/JS source sets

Kotlin/Native targets do not require additional test dependencies, and the kotlin.test API implementations are built-in.

【Kotlin】

  1. kotlin {
  2. sourceSets {
  3. val commonTest by getting {
  4. dependencies {
  5. implementation(kotlin("test")) // This brings all the platform dependencies automatically
  6. }
  7. }
  8. }
  9. }

【Groovy】

  1. kotlin {
  2. sourceSets {
  3. commonTest {
  4. dependencies {
  5. implementation kotlin("test") // This brings all the platform dependencies automatically
  6. }
  7. }
  8. }
  9. }

You can use shorthand for a dependency on a Kotlin module, for example, kotlin(“test”) for “org.jetbrains.kotlin:kotlin-test”.

配置 Gradle 项目 - 图10

You can use the kotlin-test dependency in any shared or platform-specific source set as well.

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() or useTestNG() in the test task of your build script. The following example is for a Kotlin Multiplatform project:

【Kotlin】

  1. kotlin {
  2. jvm {
  3. testRuns["test"].executionTask.configure {
  4. useJUnitPlatform()
  5. }
  6. }
  7. sourceSets {
  8. val commonTest by getting {
  9. dependencies {
  10. implementation(kotlin("test"))
  11. }
  12. }
  13. }
  14. }

【Groovy】

  1. kotlin {
  2. jvm {
  3. testRuns["test"].executionTask.configure {
  4. useJUnitPlatform()
  5. }
  6. }
  7. sourceSets {
  8. commonTest {
  9. dependencies {
  10. implementation kotlin("test")
  11. }
  12. }
  13. }
  14. }

The following example is for a JVM project:

【Kotlin】

  1. dependencies {
  2. testImplementation(kotlin("test"))
  3. }
  4. tasks {
  5. test {
  6. useTestNG()
  7. }
  8. }

【Groovy】

  1. dependencies {
  2. testImplementation 'org.jetbrains.kotlin:kotlin-test'
  3. }
  4. test {
  5. useTestNG()
  6. }

Learn how to test code using JUnit on the JVM.

If you need to use a different JVM test framework, disable automatic testing framework selection by adding the line kotlin.test.infer.jvm.variant=false to the project’s gradle.properties file. After doing this, add the framework as a Gradle dependency.

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.

Set a dependency on a kotlinx library

If you use a kotlinx library and need a platform-specific dependency, you can use platform-specific variants of libraries with suffixes such as -jvm or -js, for example, kotlinx-coroutines-core-jvm. You can also use the library’s base artifact name instead – kotlinx-coroutines-core.

【Kotlin】

  1. kotlin {
  2. sourceSets {
  3. val jvmMain by getting {
  4. dependencies {
  5. implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.7.1")
  6. }
  7. }
  8. }
  9. }

【Groovy】

  1. kotlin {
  2. sourceSets {
  3. jvmMain {
  4. dependencies {
  5. implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.7.1'
  6. }
  7. }
  8. }
  9. }

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】

  1. kotlin {
  2. sourceSets {
  3. val commonMain by getting {
  4. dependencies {
  5. implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.1")
  6. }
  7. }
  8. }
  9. }

【Groovy】

  1. kotlin {
  2. sourceSets {
  3. commonMain {
  4. dependencies {
  5. implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.1'
  6. }
  7. }
  8. }
  9. }

Set dependencies at top level

Alternatively, you can specify the dependencies at top level, using the following pattern for the configuration names: <sourceSetName><DependencyType>. This can be helpful for some Gradle built-in dependencies, like gradleApi(), localGroovy(), or gradleTestKit(), which are not available in the source sets’ dependency DSL.

【Kotlin】

  1. dependencies {
  2. "commonMainImplementation"("com.example:my-library:1.0")
  3. }

【Groovy】

  1. dependencies {
  2. commonMainImplementation 'com.example:my-library:1.0'
  3. }

下一步做什么?

Learn more about: