Kotlin
KSP processor
Learn to write a KSP processor.
How to write a processor?
To write a KSP processor, you expose it with a SymbolProcessorProvider. The provider creates a processor instance via create(environment).
The processor finds annotated symbols in process(resolver) and handles them. For each symbol, you typically call resolver.getSymbolsWithAnnotation("Entity"), collect the results, generate Kotlin code for each, and write it to the codeGenerator. In this lesson you will write a simple EntityProcessor; instead of real codegen, it will log the symbols it accepts.
Symbol filtering
A processor rarely handles all symbols; it usually picks those with a specific annotation. This is called symbol filtering.
Example: symbols.filter { it.startsWith("Entity") }.forEach { ... }. Here filter keeps only those starting with Entity; forEach runs an action for each. In real KSP this filter is done with getSymbolsWithAnnotation; in this lesson we show it on a simple List<String>. Filtering lets the processor focus on relevant symbols.
Exercise Write EntityProcessor
Define class EntityProcessor. Method fun process(symbols: List<String>) should run filter { it.startsWith("Entity") } on symbols and for each call println("processed: $it"). In main, call it with listOf("Entity:User", "Plain", "Entity:Order").
Show example solution
class EntityProcessor {
fun process(symbols: List<String>) {
symbols.filter { it.startsWith("Entity") }.forEach { println("processed: $it") }
}
}
fun main() {
EntityProcessor().process(listOf("Entity:User", "Plain", "Entity:Order"))
}
Test yourself
-
Call the process method
fun main() {
val p = EntityProcessor()
p.____(listOf("User", "Order"))
}
Show answer
fun main() {
val p = EntityProcessor()
p.process(listOf("User", "Order"))
}
-
Match processor steps
- getSymbolsWithAnnotation
- Find symbols
- filter
- Filter symbols
- forEach
- Handle each
- codeGenerator
- Write code
-
How does a processor find symbols?
- By scanning a random list
- By making an HTTP request
- Via getSymbolsWithAnnotation
- By reflection at runtime
Show answer
Via getSymbolsWithAnnotation — getSymbolsWithAnnotation finds relevant symbols at compile time.
Next lesson: KAPT