How Can We Reference Kotlin Constants in a Java An

2020-03-01 08:06发布

问题:

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?

回答1:

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!



标签: kotlin