问题
I would like to know if in an Android project mixing Java and Kotlin files we must use annotationProcessor or kapt, or both ?
In my understanding annotationProcessor must be used for Java files using annotations for code generation, and kapt must be used for Kotlin files using annotations for code generation.
I have a project mixing both languages, and I just have replaced all the annotationProcessor dependencies in the build.gradle by kapt. Surprisingly it builds and seems to run correctly but I do not understand why kapt works well even with Java files...
Can someone explain to me ?
Thank you
回答1:
First of all, the Kotlin Annotation processing tool (kapt) uses the Java compiler to run annotation processors. If your project contains any Java classes, kapt takes care of them by design. Kotlinlang recommends using kapt
incase you used annotationProcessor
from the Android Support before.
JetBrains has a nice article about how kapt works in more detail, its from 2015 but UP-TO-DATE.
回答2:
In Java you can specify annotationProcessor (or apt) dependency like below:
dependencies {
...
annotationProcessor "com.google.dagger:dagger-compiler:$dagger-version"
}
In Kotlin you have to add the kotlin-kapt
plugin to enable kapt, and then replace annotationProcessor
with kapt
:
apply plugin: 'kotlin-kapt' //Must include
dependencies {
...
kapt "com.google.dagger:dagger-compiler:$dagger-version"
}
That's all! Note that kapt takes care of your Java files as well as kotlin file, so you don't need to keep the annotationProcessor dependency.
For more details: link
来源:https://stackoverflow.com/questions/50027741/android-project-with-java-and-kotlin-files-kapt-or-annotationprocessor