190

Build.gradle.kts

buildscript {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
    dependencies {
        classpath ("com.android.tools.build:gradle:7.0.2")
        classpath ("org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.30")
        classpath("gradle.plugin.com.github.spotbugs.snom:spotbugs-gradle-plugin:${Versions.spotbugsGradlePluginVersion}")
        classpath("se.bjurr.violations:violations-gradle-plugin:${Versions.violationsVersion}")

    }
}
//android {
//    compileOptions {
//        sourceCompatibility = JavaVersion.VERSION_11
//                targetCompatibility = JavaVersion.VERSION_11
//    }
//
//    kotlinOptions {
//        jvmTarget = JavaVersion.VERSION_11.toString()
//    }
//}
plugins {
    `maven-publish`
    `java-gradle-plugin`
    `kotlin-dsl`
    id ("io.gitlab.arturbosch.detekt") version ("1.18.1")
}
repositories {
    google()
    mavenCentral()
    gradlePluginPortal()
}

dependencies {
    compileOnly(gradleApi())
    testImplementation(gradleTestKit())
    testImplementation("junit:junit:${Versions.jUnitVersion}")
}
val generatedSources = tasks.register<GenerateVersionsFileTask>("generateSources")

I get the following error:

ERROR : 'compileJava' task (current target is 11) and 'compileKotlin' task (current target is 1.8) jvm target compatibility should be set to the same Java version.

When I uncomment android {}, I get:

Error : Script compilation errors:

 Line 15: android {
           ^ Unresolved reference: android
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
jitendra kumar
  • 2,161
  • 2
  • 7
  • 12
  • Note that if you don't have any Java sources (only Kotlin sources) this message actually should not appear at all, also see https://youtrack.jetbrains.com/issue/KT-48745. – sschuberth Sep 24 '21 at 15:25
  • I believe that the "android" block not resolving is because you don't have either "com.android.application" or "com.android.library" plugin applied – Tom Rutchik Apr 27 '22 at 17:48

19 Answers19

134

We also need to pay attention to the version that the error is showing. In my case it was :

Caused by: org.gradle.api.GradleException: 'compileDebugJavaWithJavac' task (current target is 1.8) and 'compileDebugKotlin' task (current target is 17) jvm target compatibility should be set to the same Java version.

Which means,the Android Studio IDE is using 17 (You can find it in File Menu->Project Structure->SDK Location->JDK location)

And You are using 1.8 in your gradle files.

So you need to change

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

and

kotlinOptions {
    jvmTarget = '1.8'
}

to

compileOptions {
    sourceCompatibility JavaVersion.VERSION_17
    targetCompatibility JavaVersion.VERSION_17
}

and

kotlinOptions {
    jvmTarget = '17'
}

Note that

since the error showed 17, I have also switched to 17.

This happened when I upgraded gradle to 8.0.

Beware of release issues. Kindly take a backup before doing the procedure. May face issues in release aab.

Make sure to check the release apk after this procedure is done, because R8 expects things like this

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Reejesh
  • 1,745
  • 2
  • 6
  • 15
127

You can set java version for java with

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

or alternatively:

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

and for kotlin with:

tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
    kotlinOptions {
        jvmTarget = "11"
    }
}

All samples are in gradle kotlin dsl.

TWiStErRob
  • 44,762
  • 26
  • 170
  • 254
Marian
  • 2,571
  • 2
  • 9
  • 8
  • 4
    Note: when I use your `tasks.withType<>` as is, I get `Could not get unknown property 'withType' for task set of type org.gradle.api.internal.tasks.DefaultTaskContainer` . Error goes away when using `tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile) {`; so brackets instead of < >. But unfortunately, that still results in the same warning the questioner asked about ;-( – GhostCat Feb 17 '22 at 07:43
  • 1
    @GhostCat I just ran into this using a old build file that *used* to work properly (with <> not ()), after I updated the `kotlin("jvm")` version. I presumed it was a gradle API change but could not find a correct way to do this.... then at some point I put this back in (it was just commented out) and go figure, it works. :\ The only significant thing in between was an "invalidate caches and restart", because a newer version of a dependent jar was not being indexed properly. You and your two ticks imply I'm not crazy, although I presume this problem isn't easily reproduced... – CodeClown42 May 28 '22 at 15:56
  • Maybe it depends on Kotlin plugin versions. There are various moving parts here. – GhostCat Jun 06 '22 at 09:17
  • The question was for `build.gradle.kts`, `tasks.withType { ... }` is Kotlin Gradle DSL syntax, `tasks.withType(T) {` is Gradle Groovy syntax. – TWiStErRob Aug 16 '22 at 17:36
  • 1
    `java.toolchain.languageVersion.set(JavaLanguageVersion.of(17))` – k4dima Mar 15 '23 at 07:49
  • in my case, I need to apply this config for all the modules – Prasanna Narshim Jul 26 '23 at 16:12
48

@Marian's answer didn't quite help me.

I end up setting the following in the app build.gradle

android {
...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }

    kotlinOptions {
        jvmTarget=11
    }
...
}
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
LXJ
  • 1,180
  • 6
  • 18
  • 1
    Did this really work for you? I thought android was restricted to jvm 1.8! – Tom Rutchik Apr 27 '22 at 17:52
  • Since Android Gradle Plugin 7.0, Java 11 is required. And the above works for me. – LXJ Apr 27 '22 at 18:17
  • 2
    Yes, I did know that the Android gradle plugin required Java 11. That's the minimum JVM level needed for your builds. Android/compileOption/sourceCompatibiity is the jvm level that you want your android code compiled to, and that's what I understand is limited to version 1.8. I think if you use some java 11 features in your android code, I think it'll break. – Tom Rutchik Apr 28 '22 at 00:05
  • The highest version was already 11 in 2020. See: https://www.mobileit.cz/Blog/Pages/android-java-release-train.aspx – mipa May 14 '22 at 09:09
  • 23
    This doesn't work with Gradle 7.6 and AGP 7.4.0. It shows in KAPT: 'compileDebugJavaWithJavac' task (current target is 11) and 'kaptGenerateStubsDebugKotlin' task (current target is 1.8) jvm target compatibility should be set to the same Java version. By default will become an error since Gradle 8.0+! Read more: https://kotl.in/gradle/jvm/target-validation Consider using JVM toolchain: https://kotl.in/gradle/jvm/toolchain – Arcao Jan 17 '23 at 12:29
  • 5
    @Arcao I don't understand what to do there. What should I change/add/delete? – android developer Mar 04 '23 at 13:54
  • it should be `jvmTarget = "11"` – Nguyen Minh Binh May 01 '23 at 14:47
  • It worked in my case. – MD. Shafiul Alam Biplob Aug 02 '23 at 00:24
34

In order to have the 'same version of Java' in both 'Java and Kotlin',
just modify your build.gradle file like this (example given for Java 11):

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
...
android {
    ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }

    // New syntax (credit goes to ʍѳђઽ૯ท in comment)
    kotlin {
        jvmToolchain(11)
    }
/*
    FYI: Old syntax:
    kotlin {
        jvmToolchain {
            languageVersion.set(JavaLanguageVersion.of("11"))
        }
    }
    FYI: Deprecated syntax:
    kotlinOptions {
        jvmTarget = "11"
    }
*/
    ...
}

My configuration:

Gradle:

  • Android Gradle Plugin: com.android.tools.build:gradle:7.4.1
  • Gradle: 7.5 (as of ./gradle/wrapper/gradle-wrapper.properties)

Kotlin:

About new syntax:
See New method for JVM toolchain configuration

NB:
More information about Kotlin configuration regarding that matter is available here: https://blog.jetbrains.com/kotlin/2021/11/gradle-jvm-toolchain-support-in-the-kotlin-plugin/

Pascal
  • 15,257
  • 2
  • 52
  • 65
  • 4
    Actually, `kotlinOptions { jvmTarget = "11" }` would work as well; note that the value is a string. re: https://kotlinlang.org/docs/whatsnew18.html#exposing-kotlin-compiler-options-as-gradle-lazy-properties But yes, the 1.8 gradle plugin suggests: "Consider using JVM toolchain" (https://kotlinlang.org/docs/gradle-configure-project.html#gradle-java-toolchains-support), as "the kotlinOptions task input and the kotlinOptions{...} task DSL are in support mode and will be deprecated in upcoming releases." – qix Feb 14 '23 at 10:02
  • 1
    You could just pass the 11 as a parameter like this as well: `jvmToolchain(11)` – ʍѳђઽ૯ท Mar 04 '23 at 20:34
25

I had the same problem after update the Android Studio to Flamingo version, this is my new configs in the build.gradle

 compileOptions {
    sourceCompatibility JavaVersion.VERSION_17
    targetCompatibility JavaVersion.VERSION_17
}
kotlinOptions {
    jvmTarget = '17'
}
Desilio Neto
  • 484
  • 5
  • 4
12

This worked nicely for me:

kotlin {
  jvmToolchain {
    languageVersion.set(JavaLanguageVersion.of("11"))
  }
}

That way I only need to set it once.

Niklas
  • 23,674
  • 33
  • 131
  • 170
  • 2
    This was added in [Kotlin 1.5.30](https://blog.jetbrains.com/kotlin/2021/11/gradle-jvm-toolchain-support-in-the-kotlin-plugin/) and only compatible with Gradle 7.2+ – TWiStErRob Aug 16 '22 at 17:42
  • 2
    Where do I need to put it? inside of each module or in the root? – Akbolat SSS Sep 15 '22 at 11:49
  • or maybe in the buildSrc/build.gradle.kts? – Akbolat SSS Sep 15 '22 at 12:57
  • This worked for me, though I needed to cast the `languageVersion` like this: `(this as JavaToolchainSpec).languageVersion` – Andrew Coates Nov 04 '22 at 12:51
  • @AkbolatSSS I put mine in the build.gradle.kts in the root of the file (not in any sub-hierarchy). I put the suggested answer in its own block. I am using a Ktor project, but the idea is similar for Android projects (im an Android dev too) – RealityExpander Apr 08 '23 at 22:39
9

I tried with the following code first for all modules

compileOptions {
    sourceCompatibility = '1.8'
    targetCompatibility = '1.8'
}
kotlinOptions {
    jvmTarget = '1.8'
}

And after adding the following line into gradle.properties solved the issue.

kotlin.jvm.target.validation.mode = IGNORE
Devin Brown
  • 1,112
  • 10
  • 17
  • 1
    ALSO remove packages from buildgradle of all plugins as a temporary Solution. - Recommendation: remove package="io.github.zeshuaro.google_api_headers" from the source AndroidManifest.xml: C:\Users\DBS-05\AppData\Local\Pub\Cache\hosted\pub.dev\google_api_headers-1.5.0+1\android\src\main\AndroidManifest.xml. - Thanks for the Update in gradle.properties – K D May 04 '23 at 22:32
  • Good Idea, Why should we decrease the *sourceCompatibility* and *targetCompatibility* version?! I did it and solved – Hossein Kurd Jul 20 '23 at 10:08
6

If anyone keeps getting warnings about a java compilation task being set to java 1.8 you can add this to the gradle script:

afterEvaluate {
    tasks.withType<JavaCompile>().configureEach {
        sourceCompatibility = JavaVersion.VERSION_11.toString()
        targetCompatibility = JavaVersion.VERSION_11.toString()
    }
}

I was getting warnings on some java compile tasks on AS and this solved it for me.

Alejandro Moya
  • 434
  • 6
  • 11
6
allprojects {
    tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
        kotlinOptions {
            jvmTarget = JavaVersion.VERSION_1_8.toString()
        }
    }
}

by including this task in your build.gradle , tells the compiler to use the JavaVersion = 1.8 in your project.

Procrastinator
  • 2,526
  • 30
  • 27
  • 36
tejj
  • 61
  • 1
  • 2
4

Surprisingly the culprit is very simple. You need to declare your KotlinCompile task before JavaCompile. Like this

tasks {

    withType<KotlinCompile> {
    
        kotlinOptions {
            freeCompilerArgs = listOf(
                "-Xextended-compiler-checks",
                "-Xinline-classes",
                "-Xjsr305=strict",
                "-Xjvm-default=all",
                "-Xskip-prerelease-check",
            )
            apiVersion = "1.8"
            languageVersion = "1.8"
            jvmTarget = "11"
        }
    }
    
    withType<JavaCompile> {
        sourceCompatibility = "11"
        targetCompatibility = "11"
    }
}
expert
  • 29,290
  • 30
  • 110
  • 214
4

Marian's solution (see above) needs to be applied, but you may still see the same message as a warning especially if you run "gradle build" from a command line. I think if you "synch" with gradle from Android Studio, you might not see the warning message. If you still see the message after properly applying Marian's solution, it's apparently a bogus warning message. My understanding is that the bogus warning message goes away once you upgrade to using kotlin 1.6+. You can disable this bogus warning by adding the following to your gradle.properties file.

kotlin.jvm.target.validation.mode = IGNORE

I'm not recommending the use of the above, but I it certainly solves the issue of seeing the bogus warning message. If you do use it, remember to remove it when it's no longer needed.

The problem for most of us is that we can't upgrade to kotlin 1.6.21 at this time. In order to upgrade to kotlin 1.6.21 you need to upgrade to android gradle 7.4. To upgrade to android gradle 7.4 you need an Android Studio version greater than Dolphin | 2021.3.1, so you would have to use one of the preview versions of Android Studio to do that at this time.

for compatibility information, see https://developer.android.com/studio/releases/gradle-plugin and https://developer.android.com/studio/releases#android_gradle_plugin_and_android_studio_compatibility

Tom Rutchik
  • 1,183
  • 1
  • 12
  • 15
3

I had experienced the same situation and tried different variations mentioned above. The strange behavior that I was having where the project built successfully on the first attempt, but the same error resurfaced when trying to build it again.

Fortunately, I found a workaround that resolved the issue. By reverting back the Gradle version from 8.0 to 7.5, the problem was resolved, and I was able to build the project without any further errors.

PalFS
  • 731
  • 6
  • 16
  • see https://kotlinlang.org/docs/gradle-configure-project.html#apply-the-plugin . This link shows relationships between versions of KGP (kotlin gradle plugin and min/max Gradle and AGP versions. More than likely, PalFS problem and solution can be explained by compatibility table found in the link! – Tom Rutchik Aug 29 '23 at 18:30
2

This solution worked for me:

Just replace the statement (or similar to this):

kotlinOptions {
    jvmTarget = JavaVersion.VERSION_1_8.toString() 
}

with

kotlinOptions {
    jvmTarget = "1.8"
}

in all the module level build.gradle files and then sync gradle.

Hope this works. Happy Coding...!

Rahul Raina
  • 3,322
  • 25
  • 30
2

I fixed this issue by using the same Java Version:

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
    }
    kotlinOptions {
        jvmTarget = '17'
    }
ahmnouira
  • 1,607
  • 13
  • 8
1

I solved this problem by updating the configuration in the gradle.properties file.

change

distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip

to

distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip

Faqiang
  • 19
  • 1
1

One of the very similar error can be this.. Execution failed for task ':app:kaptGenerateStubsDebugKotlin'.

'compileDebugJavaWithJavac' task (current target is 1.8) and 'kaptGenerateStubsDebugKotlin' task (current target is 17) jvm target compatibility should be set to the same Java version.

First, I would ask you to go to this path in Android Studio and check what Gradle JDK versions you are using... Simply Goto ->File->Settings->Build,Execution,Development->Build Tools->Gradle Now, see inside Gradle SDK, what version is selected.

Now to fix the error open the 'build.gradle' file for your 'app module'. And to fix it, make sure to check if you have equal java version at two blocks in your 'build.gradle' . The first one is inside the 'compileOptions' , make sure the two lines have similar java versions as you have used in Gradle SDK (checked above),

compileOptions {
    sourceCompatibility JavaVersion.VERSION_11
    targetCompatibility JavaVersion.VERSION_11
}

The second block to be checked is 'kotlinOptions', check the Java version here too,

kotlinOptions {
    jvmTarget = '11'
}

And hopefully, this will solve the error.

The Droid Guy
  • 127
  • 1
  • 3
0

Pretty much all the answers are at small variations to each other, mine too.

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlin {
        jvmToolchain(8)
    }

This worked for me. Looks like tool chain defaults to different value else where, this overrides to match compile options and resolves the issue.

Saran
  • 6,274
  • 3
  • 39
  • 48
0

For anyone who did everything but still struggling with this problem, try to downgrade your gradle version. In my case I changed 8.0 to 7.5 and it helped.

0
  1. Remove package from the manifest tag in AndroidManifesty.xml
  2. add the command below into project's gradle.properties:

kotlin.jvm.target.validation.mode = IGNORE 3. make sure the kotlinOptions has been set next to compileOptions: compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' }

Hossein Kurd
  • 3,184
  • 3
  • 41
  • 71