Migrate to K2 in Compose Multiplatform

Let's see how to migrate to the new Kotlin v2.0, on a Compose Multiplatform project

avatar

Shubham Singh

kotlin
android
compose-multiplatform
upgrade-kotlin-2

JetBrains has released a stable version of the new Kotlin Compiler v2.0, also known as K2. This release features a complete rewrite of the compiler frontend from scratch, resulting in faster code compilation and smarter code analysis. Additionally, it introduces first-party support for Compose Multiplatform. As a result, the Jetpack Compose compiler will now ship along with Kotlin.

Let's now explore the process of migrating to K2 within our Compose Multiplatform project.

1. Update plugins version

We need to update the following plugins to v2.0.0 :

  • org.jetbrains.kotlin.multiplatform
  • org.jetbrains.kotlin.native.cocoapods
  • org.jetbrains.kotlin.plugin.serialization

Considering the project uses version catalog, our libs.versions.toml will look like this :

1[versions] 2 3kotlin = "2.0.0" 4 5[plugins] 6 7multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } 8cocoapods = { id = "org.jetbrains.kotlin.native.cocoapods", version.ref = "kotlin" } 9kotlinx-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }

2. Add Compose compiler

We need to add Compose compiler plugin to our project, for which we need to do following changes :

1// libs.versions.toml 2 3[plugins] 4 5... 6compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } 7...
1// build.gradle.kts 2 3plugins { 4 ... 5 alias(libs.plugins.compose.compiler).apply(false) 6 ... 7}
1// composeApp/build.gradle.kts 2 3plugins { 4 ... 5 alias(libs.plugins.compose.compiler) 6 ... 7} 8 9// enable strong skipping mode - optional 10composeCompiler { enableStrongSkippingMode = true }

3. Update gitignore

The K2 compiler adds a new folder .kotlin to cache klibs, which we need not commit, hence we need to add it to .gitignore

1... 2.kotlin 3...

After doing the above changes our project is now ready to use the goodness of K2 compiler. For reference here is my commit for K2 Migration .