0

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.

Tomás Duhourq
  • 203
  • 1
  • 2
  • 8
  • What do you mean by "this compiles"? Is that a runtime error you are showing? Looks like you are using sbt. Did you succeed to run `sbt test:compile`? I think you pretty much do need to access that symbol through `Nested.Inner$.MODULE$.x()` – 0__ Feb 29 '16 at 20:49
  • Compiles meaning `sbt clean compile` succeeds. – Tomás Duhourq Feb 29 '16 at 20:58
  • But where is `TestFromJava`, is that main sources or test sources? Is that in `src/main/java` or `src/test/java` (assuming you have an sbt build - can you confirm this?). `compile` does not compile test-sources, it's short for `compile:compile`. You need to run `test:compile`. – 0__ Feb 29 '16 at 21:03
  • Which scala version is this? If I recall you don't need the `$MODULE` for 2.11. – yw3410 Feb 29 '16 at 21:45
  • @0__ on `sbt test:compile` it complains about the same compilation error from above. @yw3410 2.11.7 scala version – Tomás Duhourq Mar 01 '16 at 12:41
  • q.e.d. - you can _not_ access those objects from Java without resolving the module fields. – 0__ Mar 01 '16 at 13:57

1 Answers1

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()
0__
  • 66,707
  • 21
  • 171
  • 266