Search code examples
androidkotlinandroid-jetpack-compose

Cannot Use Kotlin 2.0 Features After Upgrade


I upgraded my Android project to Kotlin 2.0, but I still can't use Kotlin 2.0 features. I believe I have done the integration correctly, yet I keep encountering this issue:

libs.toml

[plugins]
kotlin-compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version = "2.0.0"}

app.gradle

plugins {
  alias(libs.plugins.kotlin.compose.compiler) apply false
}

build.gradle

plugins {
    alias(libs.plugins.kotlin.compose.compiler)
}

gradle.properties

kapt.use.k2=true
ksp.useK2=true

I also removed composeOptions from the build.gradle file. However, IDE still warns me. Pls check this photo below.

enter image description here

I'm attaching the code here for you to copy

interface Status {
        fun signal() {}
    }
    
    interface Ok : Status
    interface Postponed : Status
    interface Declined : Status
    
    fun signalCheck(signalStatus: Any) {
        if (signalStatus is Postponed || signalStatus is Declined) {
            signalStatus.signal()
        }
    }

Solution

  • The code is working perfectly fine, it is just the IDE that thinks there is an error. Just run the code, you'll see it works.

    The reason for that is that the new K2 compiler of Kotlin 2.0.0 is only used by the gradle task that compiles your app while the IDE still uses the old compiler. That means that syntax highlighting, code completion and syntax verification like the above do not know about the new compiler features.

    You can also make the IDE use K2, but that is still in alpha and not everything is working yet. For IntelliJ IDEA and Android Studio follow the steps outlined here: https://kotlinlang.org/docs/whatsnew20.html#support-in-ides

    In your IDE, go to Settings | Languages & Frameworks | Kotlin and select the Enable the K2-based Kotlin plugin option. The IDE will analyze your code using its K2 Kotlin mode.

    Be aware:

    The K2 Kotlin mode is in Alpha and is available starting from 2024.1. The performance and stability of code highlighting and code completion have been significantly improved, but not all IDE features are supported yet.