KSP
- Kotlin course
- Expert
- Lesson 7/47
- 5 min
Learn the Kotlin Symbol Processing (KSP) concept.
What is KSP?
KSP (Kotlin Symbol Processing) is the Kotlin compiler's plugin mechanism; it reads source code and runs symbol processors. It is stable since Kotlin 1.6+.
A KSP module implements the SymbolProcessor interface. Each processor is called via its process(resolver) method; the resolver finds annotated symbols. KSP is up to 2x faster than KAPT; it does not convert Kotlin to Java. Room, Moshi and Hilt ship KSP support. In this lesson you will set up the basic processor skeleton.
The process(resolver) method
A KSP processor is called via process(resolver: Resolver). The resolver gives access to symbols.
The processor finds symbols with the annotations it cares about via resolver.getSymbolsWithAnnotation(...). The returned Sequence<KSAnnotated> is iterated to handle each one. Returning unprocessed symbols is common, so a later round can retry. The processor also takes a SymbolProcessorEnvironment; logger and options live there. This structure is set up for compile-time code generation.
Practice Write HelloProcessor
Define a data class SymbolProcessorEnvironment(logger: (String) -> Unit). Inside HelloProcessor(private val env: SymbolProcessorEnvironment) add fun process() that calls env.logger("KSP ready"). In main, set up the logger with println and call the processor.
Starter code
class SymbolProcessorEnvironment(val logger: (String) -> Unit)
// add the HelloProcessor class
fun main() {
val env = SymbolProcessorEnvironment { msg -> /* print msg */ }
// call the processor
}Sample solution
class HelloProcessor(private val env: SymbolProcessorEnvironment) {
fun process() {
env.logger("KSP ready")
}
}
fun main() {
val env = SymbolProcessorEnvironment { msg -> println(msg) }
HelloProcessor(env).process()
}Expected output
KSP ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is KSP's core interface?
- CoroutineScope
- SymbolProcessor Correct answer
- FlowCollector
- KoinModule
Explanation: SymbolProcessor is the interface every KSP processor implements.
2 Complete the process method
class HelloProcessor : SymbolProcessor {
override fun ____(resolver: Resolver): List<KSAnnotated> {
return emptyList()
}
}
class HelloProcessor : SymbolProcessor {
override fun process(resolver: Resolver): List<KSAnnotated> {
return emptyList()
}
}
Explanation: process(resolver) is in every KSP processor.
3 Match KSP parts
| Term | Meaning |
|---|---|
SymbolProcessor |
Processor interface |
Resolver |
Symbol access |
SymbolProcessorEnvironment |
Logger and options |
KSAnnotated |
Annotated symbol |