user1432980 user1432980 - 2 months ago 18
Scala Question

cannot find symbol MODULE$

I am trying to access Scala

object
that is nested in Scala
class


class ObjectState {

object Mirror {
def inMirrorObjectState(state: ObjectState): Unit = {
...
}
}


I am doing it like this

import com.lapots.game.journey.osm.domain.ObjectState;
public class StaticInterop {

public static void readObjectState(ObjectState objState) {
ObjectState.Mirror$.MODULE$.inMirrorObjectState(objState);
}

}


But it fails during compilation

error: cannot find symbol
ObjectState.Mirror$.MODULE$.inMirrorObjectState(objState);
^
symbol: variable MODULE$
location: class ObjectState.Mirror$


Why is that?

Answer

The reason that doesn't work is because an object inside a class is not actually a singleton. Each instance of ObjectState gets its own object.

To access that singleton you'd have to do this:

ObjectState a = new ObjectState();
//use the above instance to access the singleton inside it
a.Mirror().inMirrorObjectState(state);

If you want a true singleton inner class, you can change the outer class to an object as well:

object ObjectState {

  object Mirror {
    def inMirrorObjectState(state: ObjectState): Unit = {
      ...
    }
} 

and then it would work like this:

ObjectState.Mirror$.MODULE$.inMirrorObjectState(state);