Frage

Given the following Scala object:

object ScalaObject {
    val NAME = "Name"
}

It appears that the Scala compiler generates a parameterless method to access the NAME field. However, when I try to access this field from Java, it looks like the only way to access this field is as a parameterless method like:

System.out.println(ScalaObject$.MODULE$.NAME());

Is there a way to coax the Scala compiler to allow Java to access the val per the expected Java idiom as:

System.out.println(ScalaObject$.MODULE$.NAME);
War es hilfreich?

Lösung

Strictly, the answer is no, because scala isn't generating just a field, but a pair of methods for accessing it. However, annotating the scala val with @scala.reflect.BeanProperty will produce Java-style getter and setter methods.

so while you wouldn't be able to say (in your case)

ScalaObject$.MODULE$.NAME

You would be able to say

ScalaObject$.MODULE$.getNAME()

Which would be a more Java-like idiom, just not the one you were hoping for.

N.B. I haven't tried @BeanProperty with an all-uppercase name like that, so I'm not sure what it would actually produce.

Andere Tipps

No, because in bytecode there are different instruction to access field and invoke method. You must patch Javac then (and your IDE syntax highlighter).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top