Using KSP with Kotlin Multiplatform: a quick overview

Jacob Ras
2 min readFeb 28, 2024

KSP, Kotlin Symbol Processing, is the successor to kapt. It is used by several libraries to generate code, like Room and kotlinx-serialization. This article provides an overview on how to use external KSP processors in general. If you want to see one in action, check out Migrating to Koin Annotations in a multiplatform project.

Made-up KSP (Kotlin Symbol Processing) logo

Basic KSP API

First, add the compiler plugin to your version catalog:

// [libs.versions.toml]
[plugins]
ksp = { id ="com.google.devtools.ksp", version = "1.9.22-1.0.17" }

Use the latest release (https://github.com/google/ksp/releases) for the Kotlin version you’re using, in this example KSP 1.0.17 for Kotlin 1.9.22.

Then we can use it. One confusing thing is that normally, we have all our dependencies together in a source set’s dependencies{} block. KSP processors, however, need to be configured outside of the source sets. Here’s how that looks:

// [build.gradle.kts]
plugins {
alias(libs.plugins.ksp)
}
kotlin {
sourceSets {
commonMain.dependencies {
implementation(libs.my.other.dependencies)
// Not here...
}
}
}
dependenies {
// ... but instead: here!
add("kspCommonMainMetadata", libs.some.ksp.plugin) // Run KSP on [commonMain] code
add("kspAndroid", libs.some.ksp.plugin)
add("kspIosX64", libs.some.ksp.plugin)
add("kspIosArm64", libs.some.ksp.plugin)
add("kspIosSimulatorArm64", libs.some.ksp.plugin)
}

Note that there’s a line for each compilation target. Also note that the name for common code here is kspCommonMainMetadata. If you only want to run the annotation processor on common code and not on any target-specific code, than the lines following it can be omitted.

That’s all there is to it! You can now use the generated code. It’s easy to check what’s being generated by navigating to /build/generated/ksp/[target]/kotlin:

Generated KSP output (from Koin Annotations) in /build/generated/ksp/android/androidDebug/kotlin

In older Kotlin/KSP versions, it was necessary to manually add the KSP output as a source directory with kotlin.srcDir("build/generated/ksp/metadata/commonMain/kotlin"). That’s no longer required as it’s automatically configured now. Same goes for the dependsOn kspCommonMainKotlinMetadata workaround you might find online. That’s why it’s recommended to use the latest dependencies.

Further reading

For more advanced usage with the example of Koin Annotations, see Migrating to Koin Annotations in a multiplatform project.

--

--