Gradle Kotlin Build: JVM Compatibility Issue with Java 23 and Kotlin 2.0.20

Hi Everyone,

I’m facing a compatibility issue in my project involving Gradle, Kotlin, and Java 23. Here’s the problem:

Problem Description

Error:

Execution failed for task ':compileKotlin'.
> Inconsistent JVM-target compatibility detected for tasks 'compileJava' (23) and 'compileKotlin' (22).
  • I am using:
    • Java version: 23.0.1
    • Gradle version: 8.8
    • Kotlin Gradle Plugin version: 2.0.20
  • My build.gradle.kts is configured to align the Java toolchain to JVM 23 while Kotlin targets a supported version (JVM 20).

My build.gradle.kts File

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

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

repositories {
    mavenCentral()
}

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

tasks.test {
    useJUnitPlatform()
}

./gradlew --version


------------------------------------------------------------
Gradle 8.10.2
------------------------------------------------------------

Build time:    2024-09-23 21:28:39 UTC
Revision:      415adb9e06a516c44b391edff552fd42139443f7

Kotlin:        1.9.24
Groovy:        3.0.22
Ant:           Apache Ant(TM) version 1.10.14 compiled on August 16 2023
Launcher JVM:  23.0.1 (Oracle Corporation 23.0.1+11-39)
Daemon JVM:    C:\Program Files\Java\jdk-23 (no JDK specified, using current Java home)
OS:            Windows 11 10.0 amd64

My Main.kt File

package com.cdcadvania

//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")
    }
}

Have you tried adding this in the root of your build.gradle.kts?

kotlin {
    jvmToolchain(21) // you can try other versions here
}