Given this bit of Kotlin:
object OldTownRoad {
const val COWBOY_HATS = "from Gucci"
const val WRANGLER = "on my booty"
}
and this Java class:
public class Scrap {
@Named(OldTownRoad.COWBOY_HATS)
public void lilNasXrefs() {
System.out.println(OldTownRoad.COWBOY_HATS);
System.out.println(OldTownRoad.WRANGLER);
}
}
The compiler is happy with the println()
calls. It complains about the use of COWBOY_HATS
in the @Named
annotation, saying "Attribute value must be constant", as seen in this Android Studio 3.5.3 screenshot:
I tried @JvmStatic
and @JvmField
on those const val
declarations, but the compiler complains that neither are valid for const
properties.
I get the same results from a companion object
:
class OldTownRoad {
companion object {
const val COWBOY_HATS = "from Gucci"
const val WRANGLER = "on my booty"
}
}
Is there some other Kotlin constant syntax that works when referenced from a Java annotation?
In order to declare an annotation, we define a class and place the annotation keyword before the class one. By their nature, declarations of annotation cannot contain any code. When we declare our custom annotations, we should specify to which code elements they might apply and where they should be stored.
Just like in Java, Kotlin has repeatable annotations, which can be applied to a single code element multiple times. To make your annotation repeatable, mark its declaration with the @kotlin.
I forgot to see if this was an Android Studio bug. :facepalm:
It turns out that if you run the code, it runs fine. Android Studio 3.5.3 appears to be complaining needlessly.
I filed a bug report to try to get confirmation of the problem.
Many thanks to @natario, whose comment made me realize that this might be an IDE problem!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With