Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I access a Scala object's val without parentheses from Java?

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);
like image 727
Jeff Axelrod Avatar asked Dec 08 '11 16:12

Jeff Axelrod


1 Answers

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.

like image 157
Ian McLaird Avatar answered Sep 20 '22 03:09

Ian McLaird