39

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

gxela
  • 703
  • 1
  • 6
  • 14

2 Answers2

39

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.

UnlikePluto
  • 3,101
  • 4
  • 23
  • 33
32

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

0xAliHn
  • 18,390
  • 23
  • 91
  • 111
  • 1
    I tried adding apply plugin: 'kotlin-kapt', the application could not build, and now I can't use anything that needs kapt, any idea how to solve this @Oxalihan – Mohammad Elsayed Apr 23 '19 at 13:51
  • Is there anyway `annotationProcessor` configuration would also pick up `kotlin` files? – AouledIssa Apr 19 '20 at 16:26