KAPT
- Kotlin course
- Expert
- Lesson 9/47
- 5 min
Learn KAPT annotation processing.
What is KAPT?
KAPT (Kotlin Annotation Processing Tool) is the legacy annotation processing path for Kotlin. It first converts Kotlin to Java, then runs Java's annotation processor.
KAPT uses the javax.annotation.processing.Processor interface. Libraries like Dagger, ButterKnife and older Room use KAPT. The Kotlin-to-Java conversion step is slow, so KAPT is slow. For new projects KSP is recommended. If KAPT is still needed for old dependencies, add the kapt(...) dependency and enable the kapt plugin.
A KAPT processor example
A KAPT processor extends AbstractProcessor and implements process(annotations, roundEnv). This structure comes from Java.
Example: class EntityProcessor : AbstractProcessor() { override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean { ... } }. Here annotated elements are found via roundEnv. The processor writes a source file with Filer for each element. This structure follows Java standards; it is not Kotlin-specific. That is why KSP is both faster and more Kotlin-friendly than KAPT.
Practice Write KaptProcessor
Define class KaptProcessor. Method fun process(annotations: List<String>) should call println("apt: $it") for each annotation. In main, call it with listOf("Entity", "Dao").
Starter code
// add the KaptProcessor class
fun main() {
KaptProcessor().process(listOf("Entity", "Dao"))
}Sample solution
class KaptProcessor {
fun process(annotations: List<String>) {
for (it in annotations) println("apt: $it")
}
}
fun main() {
KaptProcessor().process(listOf("Entity", "Dao"))
}Expected output
apt: Entity apt: Dao
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match KAPT parts
| Term | Meaning |
|---|---|
KAPT |
Legacy processing path |
javax.annotation.processing |
Java APT interface |
kapt plugin |
Gradle plugin |
kapt(...) |
Dependency |
2 Why is KAPT slow?
- It uses reflection
- It launches coroutines
- It opens a network connection each time
- It first converts Kotlin to Java Correct answer
Explanation: KAPT is slow because it converts Kotlin to Java first.
3 Complete the KAPT processor class
class EntityProcessor : ____() {
override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean {
return true
}
}
class EntityProcessor : AbstractProcessor() {
override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean {
return true
}
}
Explanation: KAPT processors extend AbstractProcessor.