4

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.

scalapeno
  • 833
  • 1
  • 6
  • 13
  • 1
    What Scala version are you using? I have Scala 2.9.0.1 final and everything compiles and runs just fine. Btw, it might be a good advice to compile the annotation separately from the rest of the code... – agilesteel Jul 30 '11 at 09:07
  • I'm using 2.8.1.final - I'll try updating. – scalapeno Aug 01 '11 at 19:33
  • Just tried with 2.9.0.1, same error: scalac -version Scala compiler version 2.9.0.1 -- Copyright 2002-2011, LAMP/EPFL scalac * HelloWorld.scala:4: error: annotation argument needs to be a constant; found: Constants.WORLD @myAnn(name = Constants.WORLD) – scalapeno Aug 01 '11 at 20:15

1 Answers1

2

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.

Lukas Rytz
  • 1,894
  • 14
  • 27