kotlingradle

IntelliJ Kotlin Build System Gradle JDK 23 gives "Inconsistent JVM-target compatibility detected for tasks 'compileJava' (23) and 'compileKotlin' (22)


I am using IntelliJ and in IntelliJ I have created a new project.

When I run the program I get the following error:

Inconsistent JVM-target compatibility detected for tasks 'compileJava' (23) and 'compileKotlin' (22).

Main.kt

package com.blabla

//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
fun main() {
    val name = "Kotlin"
    //TIP Press <shortcut actionId="ShowIntentionActions"/> with your caret at the highlighted text
    // to see how IntelliJ IDEA suggests fixing it.
    println("Hello, " + name + "!")

    for (i in 1..5) {
        //TIP Press <shortcut actionId="Debug"/> to start debugging your code. We have set one <icon src="AllIcons.Debugger.Db_set_breakpoint"/> breakpoint
        // for you, but you can always add more by pressing <shortcut actionId="ToggleLineBreakpoint"/>.
        println("i = $i")
    }
}

build.gradle.kts

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

group = "com.blabla"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(kotlin("test"))
}

tasks.test {
    useJUnitPlatform()
}

What should I do to fix this issue?


Solution

  • Kotlin 2.0 can produce bytecode for Java 22 but not 23 (docs) so simply running Gradle with a JVM version 23 is going to produce the described incompatibility.

    If you want to stick with JVM version 23 you'll need to downgrade the output bytecode, which you can do by:

    java.setTargetCompatibility(22)
    
    kotlin {
        compilerOptions {
            jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_22
        }
    }
    

    Alternatively you can downgrade the JVM used for compiling the code, which is easily done with a toolchain:

    kotlin.jvmToochain(22)