Access inner class method with “fine” syntax in Java using Scala class & object

人盡茶涼 提交于 2020-01-07 02:55:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!