Kotlin
Summary - KSP and KAPT
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.
Exercise 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").
Show example 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"))
}
Test yourself
-
Which step comes first in a processor?
- Generate code
- Close the file
- Find symbols
- Finish the compile
Show answer
Find symbols — First symbols are found, then code is generated for them.
-
Complete the logger call
fun process(symbols: List<String>) {
for (it in symbols) {
____("class $it(val id: Int)")
}
}
Show answer
fun process(symbols: List<String>) {
for (it in symbols) {
logger("class $it(val id: Int)")
}
}
-
Match KSP concepts
- SymbolProcessor
- Processor interface
- Resolver
- Symbol access
- codeGenerator
- Code writing
- KAPT
- Legacy path
Next lesson: Compiler plugins