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.

3
  • 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, 2011 at 9:07
  • I'm using 2.8.1.final - I'll try updating.
    – scalapeno
    Aug 1, 2011 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 1, 2011 at 20:15

1 Answer 1

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.

1
  • The bug now says it's been fixed in Scala 2.10.
    – ebruchez
    Apr 6, 2013 at 2:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.