Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to treat scala value as constant from java

I want to define a value in my Scala code and treat this value as constant (used in annotation) within my Java code (which is calling scala).

For example:

object MyValues {
   val a = 5
}

However when I'm trying to use this value within Java annotation it gives me an error: java: attribute value must be constant

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyJavaAnnotation {
   int aValue() default MyValues.a(); // <-- Error
}

Calling it like this doesn't work either: MyValues$.MODULE$.a();

I also tried to prefix the val with a final keyword without success.

Is there a workaround for this ?

like image 929
Tal G. Avatar asked Apr 08 '14 09:04

Tal G.


1 Answers

No, as far as I know. As a workaround, you can define a Java constant which calls the method:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyJavaAnnotation {
   int aValue() default A;
   static final int A = MyValues.a();
}

I think it could be defined inside the same annotation, if not move it somewhere.

like image 96
Alexey Romanov Avatar answered Oct 01 '22 17:10

Alexey Romanov