Search code examples
androidkotlingradlekapt

Android AGP 8 + Gradle 8 + Kotlin 1.8 causes error in Kapt


I just updated to Android Studio Flamingo | 2022.2.1. Now I get this error:

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.
  Consider using JVM toolchain: https://kotl.in/gradle/jvm/toolchain

I am using the AS included Kotlin which is 1.8.0 but this was working fine with AGP 7.4.2 and Gradle 7.5 - it only broke with the Gradle and AGP update coming from AS Flamingo. Also:

  • if I downgrade Kotlin to 1.7.20 it works again
  • if I update Kotlin to 1.8.20 it gives the error above

I do have the compile options:

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }

I tried also the sample AS apps but they have Kotlin 1.7.20. They will work with Kotlin 1.8.0 too - unless you introduce kapt in dependencies! (e.g. Dagger)

So what is the combination that should work - including kapt - and has the latest stable recommended versions from Android Studio?

  • Android Studio version?
  • AGP version?
  • Gradle version?
  • Kotlin version?

Please no untested answers. I know it "should" work but it doesn't.


Solution

  • There is a compatibility issue between the latest Android Gradle plugin and Kotlin kapt. As a result, the jvmTarget that you specify in the Android configuration will be set on the Kotlin compilation tasks but not on the kapt task, which by default uses the toolchain version (currently JDK 17).

    As a workaround, set the jvmTarget on the kapt task manually (in your case, the target is Java 1.8):

    tasks.withType(org.jetbrains.kotlin.gradle.tasks.KaptGenerateStubs).configureEach {
        kotlinOptions {
            jvmTarget = "1.8"
        }
    }