KSP processor
- Kotlin course
- Expert
- Lesson 8/47
- 5 min
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.
Practice 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").
Starter code
// add the EntityProcessor class
fun main() {
EntityProcessor().process(listOf("Entity:User", "Plain", "Entity:Order"))
}Sample 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"))
}Expected output
processed: Entity:User processed: Entity:Order
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Call the process method
fun main() {
val p = EntityProcessor()
p.____(listOf("User", "Order"))
}
fun main() {
val p = EntityProcessor()
p.process(listOf("User", "Order"))
}
Explanation: processor.process(...) handles the symbols.
2 Match processor steps
| Term | Meaning |
|---|---|
getSymbolsWithAnnotation |
Find symbols |
filter |
Filter symbols |
forEach |
Handle each |
codeGenerator |
Write code |
3 How does a processor find symbols?
- By scanning a random list
- By making an HTTP request
- Via getSymbolsWithAnnotation Correct answer
- By reflection at runtime
Explanation: getSymbolsWithAnnotation finds relevant symbols at compile time.