Search code examples
scalaannotationscross-language

Cannot use java value as parameter to java annotation on scala function


I have 3 java files: HW.java, myAnn.java, and Constants.java in package myApp.

Constants.java:

public final class Constants {
    public static final String WORLD ="World";
}

myAnn.java:

public @interface myAnn {
    java.lang.String name() default "";
}

HW.java:

class HW {
    @myAnn(name = Constants.WORLD)
    public static void main(String[] args){
        System.out.println("Hi "+ Constants.WORLD);
    }
}

My app compiles and runs fine as shown above, but I want to migrate HW.java to scala as HelloWorld.scala:

object HelloWorld {
  @myAnn(name = Constants.WORLD)
  def main(args: Array[String]) {
    println("Hello " + Constants.WORLD)
  }
}

When I try to compile this, I get

error: annotation argument needs to be a constant; found: Constants.WORLD @myAnn(name = Constants.WORLD)

If I remove the annotation then HelloWorld compiles and executes as expected.

Why can I use Constants.WORLD as a parameter to an annotation from a java program, but not from a scala program? Is there something I can modify in Constants.java to allow it to be used from either java or scala? I can't modify MyAnn.java, and I can't migrate Constants.java yet.


Solution

  • It is a bug that only shows up when feeding the java source files into the scala compiler, see issue SI-2764. The example works when compiling the java files first using javac and then pointing scalac's classpath to the generated classfiles.