Skip to content

Using KSP with Kotlin Multiplatform: a quick overview

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.

Basic KSP API

First, add the compiler plugin to your version catalog:

[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:

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

Further reading

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

You can reply to this article at https://medium.com/@jacobras/using-ksp-with-kotlin-multiplatform-a-quick-overview-6b858df77b5f