CodeGym /Courses /Kotlin SELF /KSP instead of runtime reflection: annotation → generatio...

KSP instead of runtime reflection: annotation → generation → code

Kotlin SELF
Level 61, Lesson 2
Available

1. Introduction

If you’ve only just gotten used to the idea of “wow, I can find a method by name and call it”, it’s perfectly natural to want to apply it everywhere: auto-commands in a CLI, auto-generating help, “plugging in plugins”, “avoiding a manual function registry”… and so on.

The problem is that runtime reflection is like trying to find an object in a room with the lights off: it’s generally possible, but you’ll keep smashing your little toe into a stool. Even if you wrote everything carefully, reflection almost always means extra work at runtime: lookup, checks, argument boxing, error handling, debugging complexity. Plus, you inevitably start depending on strings, and strings, as we know, can’t “turn red” in the IDE when you made a mistake inside them.

And that’s where a good engineering question shows up: “Can we make the computer do the boring work for us, but before the program even starts?”

KSP: what it is in plain terms

KSP (Kotlin Symbol Processing) is a mechanism that lets you, at compile time, walk through your Kotlin code, find the elements you need (classes, functions, properties)—usually marked with annotations—and generate new Kotlin code (.kt files). After generation, the compiler simply compiles these files together with your project, as if you had written them by hand.

The key idea here: KSP doesn’t “speed up compilation for the sake of compilation” and doesn’t “replace Kotlin”. It adds a stage: detect the needed elements → generate sources → then proceed with normal compilation.

If reflection is like “we run the program, and during execution we ask: ‘Hey object, what methods do you have?’”, then KSP is “before we run, we compiled a directory of what methods exist, and at runtime we just read the directory”.

2. The main flow: “annotation → generation → plain code”

Next comes an important “mental model”. Try to see it as an assembly line diagram: raw material in, finished part out.

Assembly line diagram

Suppose we have the project sources, and we want part of the code to “self-wire”. Then the overall pipeline looks roughly like this:

flowchart TD
    A["Your sources (.kt)"] --> B["KSP: symbol analysis (classes/functions/annotations)"]
    B --> C["Generated .kt files (build/generated/...)"]
    C --> D["Normal Kotlin compilation"]
    D --> E["Bytecode / JAR"]
    E --> F["Run: plain Kotlin code without reflection"]

The key meaning: KSP does the work where the compiler “can see everything”, and at runtime “there’s nothing left to search for”.

An annotation is just a marker

A very common beginner confusion: “I added an annotation—why didn’t anything happen?”

Because an annotation by itself is just a marker. It only starts to “mean something” if there is a tool that reads that marker and acts on it (in our case, a KSP processor/generator).

The simplest marker annotation can look like this:

@Target(AnnotationTarget.FUNCTION)
annotation class CliCommand(val name: String)

By itself, it won’t add a command to your application. But it gives the generator a clear signal: “This is a command—process it”.

4. Practical example: a CLI “manually”, “via reflection”, and “via KSP”

So KSP doesn’t remain an abstract build-world term, let’s tie it to our training console application. Suppose we keep evolving a CLI app (let’s call it BudgetCli), where there are commands like "add", "list", "help".

Manual command registry

The classic “simple” way is to create a Map<String, (List<String>) -> Unit> and register commands manually. It works, but it looks like bookkeeping: useful, but not joyful.

typealias CommandHandler = (List<String>) -> Unit

val commands: Map<String, CommandHandler> = mapOf(
    "help" to ::cmdHelp,
    "list" to ::cmdList
)

The issue here isn’t strings themselves, but the fact that you must remember to register things. You added cmdAdd()—didn’t add it to the Map—the command “kind of exists”, but “kind of doesn’t”.

Runtime reflection as an auto-scanner

After a lecture on reflection, the temptation appears: “Let’s find all functions annotated with @CliCommand at runtime!”

The idea sounds nice, but it has a cost: at runtime you need to search, filter, and handle errors. And if you select by a string—method name or annotation name—you’re back to living in the world of strings.

We won’t dive into implementing such a scanner here (that was in the previous lesson), but it’s important to lock in the idea: runtime reflection is “auto-assembling commands on the spot”, right at startup.

KSP approach: commands are “assembled” before startup

Now we do the same, but in the KSP style: we want to mark command functions with an annotation, and then get a generated registry.

Step 1. Write the annotation

@Target(AnnotationTarget.FUNCTION)
annotation class CliCommand(val name: String)

Step 2. Mark command functions

Let’s assume we have a file Commands.kt:

@CliCommand("help")
fun cmdHelp(args: List<String>) {
    println("Commands: help, list") // Commands: help, list
}

@CliCommand("list")
fun cmdList(args: List<String>) {
    println("List is empty for now") // List is empty for now
}

Step 3. What KSP “conceptually” generates

Important note: we are not writing a KSP processor in this course. But we can still understand what code should come out “as output”.

For example, the generator might create a file GeneratedCliRegistry.kt:

typealias CommandHandler = (List<String>) -> Unit

object GeneratedCliRegistry {
    val commands: Map<String, CommandHandler> = mapOf(
        "help" to ::cmdHelp,
        "list" to ::cmdList
    )
}

Notice something nice: ::cmdHelp is a regular callable reference that the compiler will validate. If you rename cmdHelp, and generation (or the generator) doesn’t match the new names, you’ll get a compile error—not a “command not found” at runtime. That’s the fundamental difference.

Step 4. Use the registry in main

fun runCommand(line: String) {
    val parts = line.trim().split(" ").filter { it.isNotBlank() }
    val name = parts.firstOrNull() ?: return
    val args = parts.drop(1)

    val handler = GeneratedCliRegistry.commands[name]
    handler?.invoke(args) ?: println("Unknown command: $name")
}

And here comes the “moment of truth”: at runtime we no longer search for functions via reflection. We simply fetch the handler from the Map and call it. Fast, predictable, type-safe (as much as is possible for a Map<String, ...>).

5. Why generated code is a strong idea

It’s easy to “fall in love” with KSP, because it promises automation without runtime magic. But it’s better to keep an honest balance in mind from the start.

Pros: speed and predictability

When KSP generates Kotlin code, the normal compiler takes over: it checks types, visibility, signatures, and function existence. What could have “blown up on the user” in runtime reflection fails at build time here—and that’s almost always cheaper and safer.

As a nice bonus, you can generate not only command registries, but also help text for help, serialization tables, field mappings, adapters, and other boring chunks that humans typically write mechanically.

Cons: the build becomes more complex

KSP is a tool that lives next to the compiler. Therefore, it is sensitive to Kotlin versions, Gradle plugins, and the environment.

This does not mean “KSP is bad”. It means “KSP is part of the build ecosystem”, and the build is also part of the product: it must be maintained, updated carefully, and verified.

6. How to choose an approach and design generation

It’s very tempting to have a “universal hammer”. But in engineering, a universal hammer quickly turns into a universal problem.

Selection table

Task What’s better Why
Code structure is known at compile time; you need to “auto-wire” elements (commands, mapping, registries) KSP You can generate plain Kotlin code, get compiler validation, and runtime speed
Structure is unknown until runtime (for example, data comes from outside, plugins are loaded from files) Runtime approaches (sometimes reflection) You can’t generate ahead of time a list of things that don’t exist yet
Simple logic is enough; 2–3 commands; an educational project “Manually” The cheapest option in terms of complexity: less build magic, easier to explain and maintain
You need type metadata for diagnostics/logs Minimal reflection (::class) Sometimes KClass.simpleName is enough, and it doesn’t turn into a system

The point of the table is not to “ban” something. The point is to understand: KSP is a great tool when you truly benefit from generation. But if you’re writing a single 200-line file, a generator can be more complex than the problem.

Why generation often produces extension functions

There is a popular code generation style: KSP generates extension functions so your code looks “native”, as if it were part of the API.

For example, instead of GeneratedCliRegistry.formatHelp() you can generate:

fun String.toCommandName(): String = trim().lowercase()

Or for a model:

data class Expense(val title: String, val amount: Int)

fun Expense.toLogLine(): String = "Expense(title=$title, amount=$amount)"

Why is this convenient? Because extension functions in Kotlin are resolved statically, at compile time: the compiler chooses which extension function to call based on the declared type, not “at runtime by miracle”. This is one reason why generated code is usually fast and predictable.

Another plus of the extension style: it helps avoid building gigantic GeneratedUtil123 classes. You get small functions next to the types they are intended for, and the IDE gives you autocompletion as usual.

How to “think in KSP”: a contract matters more than guesses

When people design generation for the first time, they often want to “be smart”: make the generator figure it out, fix it, come up with a name, handle all edge cases. This usually ends with the generator starting to look like a second compiler… only worse (because it’s yours).

A healthy approach to KSP is to treat it like a strict assembly line: you feed clear rules (a contract) as input, and you get very predictable code as output.

For example, for our CLI commands we can agree on a contract in advance:

The command text is specified in @CliCommand("name"), the function must have the signature (List<String>) -> Unit, and all commands are collected into GeneratedCliRegistry.commands. That’s it.

No “if the function has no args, I’ll take it too”, no “if there are two identical names, I’ll pick the last one”. Those “kind guesses” usually turn into an un-debuggable lottery.

7. Common mistakes when using the KSP idea

Mistake #1: expecting the annotation to “do something by itself”.
It’s very easy to put @CliCommand above a function and wait for the command to appear. But an annotation is just a marker in code. Until a handler (generator) is added to the project, nothing happens—and that’s normal. Keep this model in your head: “an annotation is input data for a tool”.

Mistake #2: trying to make the generator a replacement for architecture.
Sometimes people start generating everything: business logic, algorithms, half the app. This quickly leads to the project becoming “a build around generation” rather than “generation around the project”. A good generator usually automates boring glue: registration, simple adapters, repetitive code. If the generator is making meaningful decisions for you, that’s a warning sign.

Mistake #3: overly “smart” rules and implicit priorities.
Once rules like “if there are two options, pick the most suitable one” show up in generation, you’ll have to explain what “suitable” means and why today one was chosen but tomorrow another. In practice, it’s better when the generator either does exactly what you said, or fails with a clear error and asks you to fix the input data.

Mistake #4: no fail-fast behavior on conflicts.
If two functions are marked with @CliCommand("list"), the generator should not “resolve it somehow”; it should stop the build and explain the conflict. Otherwise you’ll get a situation where the app starts, the “wrong” command works, and you spend half a day thinking there’s a bug in your logic, when in fact it’s a registration bug.

Mistake #5: version dependency and ignoring that the build is part of the product.
KSP lives next to the compiler and Gradle infrastructure, so it is sensitive to updates. This is not a scare tactic; it’s the reality of tools at this level: if a project uses generation, “updating Kotlin randomly” is no longer a minor thing—it’s an event that requires attention.

Mistake #6: generating an API that cannot be used without reading the generator sources.
Generated code is also an API. If you generate weird names, unexpected classes, and confusing signatures, it will be hard to use—even for you a month later. A good style is to generate minimal, readable Kotlin that you wouldn’t be ashamed to show to a person.

Mistake #7: believing that “generated code must not be touched”.
You really shouldn’t edit it by hand (because it will be regenerated), but you must be able to read it. When something breaks, the most practical skill is to open the generated .kt files and see: “What exactly did it produce?” This is often faster than any assumptions and guesswork.

1
Task
Kotlin SELF, level 61, lesson 2
Locked
Hello command
Hello command
1
Task
Kotlin SELF, level 61, lesson 2
Locked
Command set
Command set
1
Task
Kotlin SELF, level 61, lesson 2
Locked
Strict Registry
Strict Registry
1
Task
Kotlin SELF, level 61, lesson 2
Locked
Help generator
Help generator
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION