13
votes

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?

1
final val?.....Rick Sanchez
Which Kotlin version are you using? I can't reproduce this.natario
@RickSanchez: final const val results in "final is a redundant modifier". Neither that nor final val clear up the problem.CommonsWare
@natario: Kotlin 1.3.61CommonsWare
@natario: Thanks for pointing out that you couldn't repro it! It appears this is a rogue Android Studio inspection error -- the code compiles fine.CommonsWare

1 Answers

11
votes

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!