Target specific JVM with Kotlin and Gradle

Viewed 301

What is the difference between

java {
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11
}

and

compileKotlin {
    kotlinOptions {
        jvmTarget = "11"
    }
}

Will they both achive the same end result in a gradle/Kotlin-library? jvmTarget is for setting which standardlibrary version to use, I understood.

1 Answers

kotlinOptions.jvmTarget is used for specifying a version of the JVM standard library used as a dependency for the compilation of JVM-specific Kotlin source sets (see https://kotlinlang.org/docs/gradle.html#dependency-on-the-standard-library and -bootclasspath option of javac).

java.sourceCompatibility ensures that .java files are using the specified version of the Java programming language syntax

java.targetCompatibility ensures that the generated .class files will be compatible with the specified JVM

So, these options are not equivalent.

Anyway, the modern (since Gradle 6.7+ and Kotlin 1.5.30+) way of defining cross-compilation parameters is a toolchain:

kotlin {
    jvmToolchain {
        (this as JavaToolchainSpec).languageVersion.set(JavaLanguageVersion.of(11))
    }
}

// Or its eqivalent:

java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(11))
    }
}
Related