I have a custom annotation processor that does roughly this:
- generate an annotation type (classes using this type are deferred until later rounds)
- in a later round, process the classes using this type and generate some more files for them
This has worked well so far in Java. But recently, I've been converting some of my classes from Java to Kotlin. The setup is still the same. But when I converted a class using the generated annotation type to Kotlin, this error popped up:
error: incompatible types: NonExistentClass cannot be converted to Annotation @error.NonExistentClass()
It's worth noting that this only happens when the file is in Kotlin - other (Java) files also use the same annotation, and they don't produce an error when I remove the annotation from the Kotlin file.
After some googling, I found out that the recommended solution is to add an option to the build.gradle
:
kapt {
correctErrorTypes = true
}
However, using this did not fix the problem. I looked at the generated stub file, and it's clear that kapt
keeps putting error.NonExistentClass
in there despite the setting:
package my.pckg;
import my.pckg.GeneratedAnnotation;
@kotlin.Metadata(...)
public final class MyClass {
private int myAnnotatedField;
@error.NonExistentClass()
public static void myAnnotatedField$annotations() {
}
public final int getMyAnnotatedField() {
return 0;
}
public final void setMyAnnotatedField(int p0) {
}
//...
}
I think it's worth noting that:
- the stub kept the correct import for the generated annotation
kapt
moved the annotation to a static method, while the original generated annotation supports only fields
MyClass
looks like this:
package my.pckg
import my.pckg.GeneratedAnnotation
class MyClass {
@GeneratedAnnotation
var myAnnotatedField: Int = 0
//...
}
And here's the build.gradle
:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
//...
kotlinOptions {
jvmTarget = '1.8'
}
}
kapt {
correctErrorTypes = true
}
dependencies {
kapt 'custom.annotation.processor'
implementation "androidx.core:core-ktx:+"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.41"
//...
}
There have been other people with this problem on SO, but none of the solutions suggested there have fixed it for me.
Edit: I have done some more testing, and discovered that the generated type is only replaced by error.NonExistentClass
when the type is used as an annotation (as an object type or even generics argument it works fine). At this point I believe this may simply be a kapt
bug.