Summary - KSP and KAPT
- Kotlin course
- Expert
- Lesson 12/47
- 5 min
Combine KSP processor, KAPT and code generation to write an annotation processor.
Summary - KSP and KAPT
In this group you learned KSP, writing a processor, KAPT, comparing the two, and generated code. Now you will write a processor that combines them.
Your EntityProcessor will take a list of symbols; for each it will generate a Kotlin class text and write it to the logger. This is a simplified model of KSP processor + code generation. In real KSP the codeGenerator writes a file; here we print to the screen via the logger.
Combining: generator processor
Now we will write an EntityProcessor that combines the KSP processor skeleton and code generation. The processor takes symbols; for each it produces a Kotlin class text; it writes to the logger.
Example: class EntityProcessor(private val logger: (String) -> Unit). fun process(symbols: List<String>) should call logger("class $it(val id: Int)") for each symbol. This models what KSP does with codeGenerator.createNewFile in a simpler way. In real KSP codeGenerator returns an OutputStream; here we use a logger directly.
Practice Write EntityProcessor + generator
Define class EntityProcessor(private val logger: (String) -> Unit). Method fun process(symbols: List<String>) should call logger("class $it(val id: Int)") for each symbol. In main, create a processor with logger = { msg -> println(msg) } and call it with listOf("User", "Order").
Starter code
// add the EntityProcessor class (takes logger)
fun main() {
val p = EntityProcessor { msg -> /* print msg */ }
p.process(listOf("User", "Order"))
}Sample solution
class EntityProcessor(private val logger: (String) -> Unit) {
fun process(symbols: List<String>) {
for (it in symbols) logger("class $it(val id: Int)")
}
}
fun main() {
val p = EntityProcessor { msg -> println(msg) }
p.process(listOf("User", "Order"))
}Expected output
class User(val id: Int) class Order(val id: Int)
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which step comes first in a processor?
- Generate code
- Close the file
- Find symbols Correct answer
- Finish the compile
Explanation: First symbols are found, then code is generated for them.
2 Complete the logger call
fun process(symbols: List<String>) {
for (it in symbols) {
____("class $it(val id: Int)")
}
}
fun process(symbols: List<String>) {
for (it in symbols) {
logger("class $it(val id: Int)")
}
}
Explanation: logger writes the generated code to the screen.
3 Match KSP concepts
| Term | Meaning |
|---|---|
SymbolProcessor |
Processor interface |
Resolver |
Symbol access |
codeGenerator |
Code writing |
KAPT |
Legacy path |