简体   繁体   中英

How to set “sourceCompatibility” for Kotlin and Gradle?

I'm getting java.lang.NoClassDefFoundError on a Android app. I managed to isolate the issue to a call to List::replaceAll . The problem is that method is for Java 8 and is not available in some devices, and Kotlin/Gradle is compiling it successfully.

Similar issue: java.lang.NoClassDefFoundError $$inlined$forEach$lambda$1 in Kotlin

My question is. Is there a way to give me a compilation error any time I use Java 8 SDK in my project? I've tried to manually set Java 1.7 like below, but the code with Java 8 compiles successfully.

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
    sourceCompatibility = JavaVersion.VERSION_1_7 // Is it even relevant here?
    targetCompatibility = JavaVersion.VERSION_1_7

    kotlinOptions {
        jvmTarget = "1.6"
    }
}

Also important, the code is not in a Android module. My Android module doesn't let me use that method, as expected.

I know this is an old question, but still may help other people.

The problem you have is because you are actually compiling your code against jdk whit is not your target. And that very particular jdk contains stream API thus compiles correctly. To achieve your goal you have to compile against your target jdk.

Kotlin documentation gives you jdkHome property. So you can:

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
    kotlinOptions {
        jdkHome = 'target/jdk/home'
    }
}

To make the solution compatible with other people in your team, you can load the path from, for example, local.properties file which should not be in your vcs:

Properties localProperties = new Properties()
localProperties.load(project.rootProject.file('local.properties').newDataInputStream())

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
    kotlinOptions {
        jdkHome = "${localProperties.getProperty('targetjdk.dir')}"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM