Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can We Reference Kotlin Constants in a Java Annotation Declaration?

Tags:

kotlin

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:

Kotlin error

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?

like image 602
CommonsWare Avatar asked Dec 27 '19 16:12

CommonsWare


People also ask

How do you use Kotlin annotations?

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.

What symbol is used for annotations Kotlin?

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.


1 Answers

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!

like image 176
CommonsWare Avatar answered Nov 02 '22 06:11

CommonsWare