Configuring your sourceCompatibility
, targetCompatibility
and kotlinOptions.jvmTarget
all at once
Oct 11, 2023
Recently I learnt a trick that you can set sourceCompatibility
, targetCompatibility
and kotlinOptions.jvmTarget
all at once:
Step 1: In your root project’s build.gradle.kts
, add the following script:
val jvmVersion: Provider<String> = providers.gradleProperty("kotlin.jvm.target")
configure(subprojects) {
// Apply compileOptions to subprojects
plugins.withType<com.android.build.gradle.BasePlugin>().configureEach {
extensions.findByType<com.android.build.gradle.BaseExtension>()?.apply {
jvmVersion.map { JavaVersion.toVersion(it) }.orNull?.let {
compileOptions {
sourceCompatibility = it
targetCompatibility = it
}
}
}
}
// Apply kotlinOptions.jvmTarget to subprojects
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
kotlinOptions {
if (jvmVersion.isPresent) jvmTarget = jvmVersion.get()
}
}
}
Step 2: In your gradle.properties
, add the following line:
kotlin.jvm.target=17
Step 3: Now you can remove all sourceCompatibility
, targetCompatibility
and kotlinOptions.jvmTarget
from your subprojects.
Done, now you can enjoy single source of truth for your subprojects!