Kotlin Multiplatform (KMP) documentation for adding a shared module to an existing project is great. It's concise, practical, and focused on getting things done. But sometimes there are some (reasonable) assumptions that if do not hold true might cost you a significant amount of time to figure out.
During my experimentation with KMP, I stumbled upon such an issue. You see I tried to add a shared Kotlin module in an existing Android app. I followed the documentation but it failed in the very first and most basic step: creating a multiplatform module. Nevertheless, I learned useful things that I want to share that might save you some time in your KMP journey.
So the documentation instructs you to install the Kotlin Multiplatform Mobile plugin, and then create a new "Kotlin Multiplatform Shared Module". You will end up with a new module with its own build.gradle.kts
. The problem is that the file is intended for projects that are not using the Gradle Version Catalog. If your Android project is using this newer way of handling dependencies, the Gradle sync will fail for this new shared module.
The problem seems to be that the build file's plugin
section does not contain any versions for the plugins:
plugins {
kotlin("multiplatform")
id("com.android.library")
}
[...]
An easy fix would be to just set the specific versions for these plugin declarations:
plugins {
// The Kotlin version you use in your Android project
kotlin("multiplatform") version "1.8.21"
// The Android Gradle Plugin version you use your Android project
id("com.android.library") version "8.0.2"
}
[...]
But the proper way to fix this, since you are using Gradle Version Catalog, is to declare them in your libs.versions.toml
:
[versions]
androidGradlePlugin = "8.0.2"
kotlin = "1.8.21"
[plugins]
android-library = { id = "com.android.library", version.ref = "androidGradlePlugin" }
kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
libs.versions.toml
And then modify the build.gradle.kts
as follow:
@Suppress("DSL_SCOPE_VIOLATION") // Remove when fixed https://youtrack.jetbrains.com/issue/KTIJ-19369
plugins {
alias(libs.plugins.kotlin.multiplatform)
alias(libs.plugins.android.library)
}
build.gradle.kts
These changes will make the Gradle sync succeed and you will ensure that the versions for the plugins stay synced across the project.
Hopefully, this will save you some time in your KMP journey.
Happy coding!
Oldest comments (0)