Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android project with Java and Kotlin files, kapt or annotationProcessor?

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

like image 767
gxela Avatar asked Apr 25 '18 17:04

gxela


People also ask

What is kotlin kapt used for?

What is KAPT used for? The answer to this is straight, it is used for annotation processing in Kotlin.

Is kapt deprecated?

app: Original kapt is deprecated.

What is kotlin annotation processor?

KSP is a powerful tool that helps developers to write light-weight compiler plugins and annotation processors while maintaining a Kotlin-friendly API. Using KSP can help developers and tech leaders to create libraries that help them achieve more productivity by generating files and boilerplate code.

What is an annotation processor?

Annotation processing is a tool built into javac for scanning and processing annotations at compile time. It can create new source files; however, it can't modify existing ones. It's done in rounds. The first round starts when the compilation reaches the pre-compile phase.


2 Answers

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.

like image 50
UnlikePluto Avatar answered Oct 06 '22 01:10

UnlikePluto


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

like image 40
0xAliHn Avatar answered Oct 05 '22 23:10

0xAliHn