Skip to Content
Course content

55: Kotlin Symbol Processing (KSP) Basics

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're an architect overseeing a massive construction project. You have hundreds of blueprints, but you don't want to manually check every single room to see if it needs a smoke detector. Instead, you tell your team: "Any room that has a red 'FIRE-SAFE' stamp on the blueprint needs a corresponding entry in the Master Safety Log."

You aren't changing the blueprints themselves; you're scanning them for specific markers and, based on those markers, generating a separate document—the Safety Log—that the builders use on-site. That is exactly what Kotlin Symbol Processing (KSP) does for your code.

Mapping the Blueprint to the Compiler

In this scenario, your blueprints are your Kotlin source files. The red stamps are annotations (like @Route or @Inject). The architect/inspector is the KSP processor, and the Safety Log is the generated Kotlin code that KSP spits out during the compilation process.

I've spent years using KAPT (Kotlin Annotation Processing Tool), and if you've used it, you know it's essentially a wrapper around Java's APT. It forces Kotlin code to be turned into Java stubs first, which is slow—painfully slow in large projects. KSP is the "native" way. It reads Kotlin symbols directly, making it significantly faster and more aware of Kotlin-specific features like nullability and sealed classes.

Scanning for Symbols

To get KSP working, you don't just write a function; you implement a SymbolProcessor. The heart of this is the process method. This is where you tell KSP, "Find me every class marked with this specific annotation."


class RouteProcessor(
    private val codeGenerator: CodeGenerator,
    private val logger: KSPLogger
) : SymbolProcessor {
    override fun process(resolver: Resolver): List<KSAnnotated> {
        // We ask the resolver to find all symbols annotated with @Route
        val symbols = resolver.getSymbolsWithAnnotation("com.example.Route")
        
        val unableToProcess = symbols.filterNot { it.validate() }.toList()
        
        symbols.filter { it is KSClassDeclaration }
            .forEach { it.accept(RouteVisitor(), Unit) }

        return unableToProcess
    }
}

Notice the Resolver. It's your window into the codebase. You don't iterate through files manually; you ask the resolver for the symbols you care about. I usually recommend returning "unable to process" symbols in the list so KSP can try again in the next round if those symbols were generated by another processor.

Turning Symbols into Source Code

Once you've found a class (a KSClassDeclaration), you want to do something with it. In my example, if I find a class marked @Route, I want to generate a registry file that maps a URL string to that class. This is where the CodeGenerator comes in.

You don't typically write raw strings for huge files—that's a recipe for syntax errors. While you can use PrintWriter, most of us use KotlinPoet alongside KSP. You define the properties and functions using KotlinPoet's DSL, and then you tell KSP to save that file to the disk.


// Inside a Visitor or the process loop
val className = classDeclaration.simpleName.asString()
val packageName = classDeclaration.packageName.asString()

val fileSpec = FileSpec.builder(packageName, "${className}RouteHelper")
    .addFunction(
        FunSpec.builder("getRoutePath")
            .returns(String::class)
            .addStatement("return \"/api/v1/%S\"", className.lowercase())
            .build()
    )
    .build()

fileSpec.writeTo(codeGenerator, Dependencies(false, classDeclaration.containingFile!!))

The Dependencies argument is crucial. It tells KSP, "If UserRoute.kt changes, you need to re-generate UserRouteHelper.kt." If you forget this, you'll run into those nightmare scenarios where you change your code, but the generated files are out of sync, and you're staring at a compiler error that makes no sense.

The Provider Bridge

KSP doesn't just magically find your SymbolProcessor. You need a SymbolProcessorProvider. This is a factory class that KSP's runtime uses to instantiate your processor. You'll register this provider in a service file (usually via META-INF/services or a Gradle plugin), which acts as the "handshake" between the Kotlin compiler and your custom logic.




📋 Practical Task

Build a "Module Registry" Generator

Your task is to create a KSP processor that automates the registration of "Feature Modules." Instead of manually adding every new feature class to a central list, you will generate that list automatically.

The Requirements:

  • Create an annotation called @FeatureModule.
  • Implement a SymbolProcessor that finds all classes annotated with @FeatureModule.
  • For every annotated class found, generate a new Kotlin file named [ClassName]Registry.kt.
  • This generated file must contain a single object called ModuleRegistry with a function getModuleName() that returns the name of the class as a string.
  • Ensure you use the CodeGenerator and properly link the Dependencies to the original source file so that changes trigger a re-generation.

Verification: Add @FeatureModule to two different classes (e.g., PaymentModule and ProfileModule). Run the build and verify that two separate registry files were created in the build/generated/ksp directory.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.