问题
I have the following scala example:
class Nested {}
object Nested {
class Inner {}
object Inner {
def x = 321
}
}
With a JUnit test to test specifically that I can do Nested.Inner.x()
and call the method freely without the Nested.Inner$.MODULE$.x()
:
import static junit.framework.Assert.*;
import org.junit.Test;
public class TestFromJava {
@Test
public void accessTest() {
assertEquals(321, Nested.Inner.x());
}
}
This compiles, but at the moment of running the test, I am getting (sbt test
):
[error] TestFromJava.java:8: cannot find symbol
[error] symbol: method x()
[error] location: class Nested.Inner
[error] Nested.Inner.x
How can I benefit from both Scala syntax and not using the horrible $? Maybe it is a feature of the language as how it generates the object
instances.
回答1:
You have to qualify singleton object
access when calling from Java, as explained in this question.
In your case that would be
Nested.Inner$.MODULE$.x()
来源:https://stackoverflow.com/questions/35709154/access-inner-class-method-with-fine-syntax-in-java-using-scala-class-object