Home > database >  "Unresolved reference: sourceCompatibility" after upgrading Gradle build to Kotlin 1.7.0
"Unresolved reference: sourceCompatibility" after upgrading Gradle build to Kotlin 1.7.0

Time:06-20

Following some answers at Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6 I have a Kotlin Gradle DSL script containing

tasks.compileKotlin {
    sourceCompatibility = JavaVersion.VERSION_11.toString()
    targetCompatibility = JavaVersion.VERSION_11.toString()

    kotlinOptions {
        jvmTarget = "11"
    }
}

but after upgrading to Kotlin 1.7.0 I get the exception

Unresolved reference: sourceCompatibility
Unresolved reference: targetCompatibility

It is clear to me they have apparently removed these, as I found it listed at https://kotlinlang.org/docs/whatsnew17.html#changes-in-compile-tasks

My question is, what do I replace it with? How should I ensure to keep compatibility?

CodePudding user response:

Setting the JVM target, and the Kotlin API and Language versions can be done by configuring all KotlinCompile tasks.

// build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
  kotlin("jvm") version "1.7.0"
}

// configure all Kotlin compilation tasks, 
// using the Gradle configuration avoidance API
tasks.withType<KotlinCompile>().configureEach {

  kotlinOptions {
    jvmTarget = "11"
    apiVersion = "1.6"
    languageVersion = "1.6"
  }

  // you can also add additional compiler args, 
  // like opting in to experimental features
  kotlinOptions.freeCompilerArgs  = listOf(
    "-opt-in=kotlin.RequiresOptIn",
  )
}
  • apiVersion restricts the use of declarations to those from the specified version of bundled libraries
  • languageVersion means the compiled code will be compatible with the specified version of Kotlin

All the compiler options are documented here. There is also additional documentation for other build tools, like Maven and Ant.

You can use the new Toolchains feature to set the version of Java that will be used to compile the project.

// build.gradle.kts
kotlin {
  jvmToolchain {
    languageVersion.set(JavaLanguageVersion.of("11"))
  }
}

Read more: Gradle Java toolchains support

  • Related