scala object and static forwarder
In scala, object is singleton where the class has only one instance. But there’s no direct singleton type(structure) in java, how does scala implement the singleton type and still keep compatible with java?
Scala compiles to java byte code and translates to java structures for the goal of interoperability with java. The common way to implement singleton in java is to mark the constructor private and keep a static reference to the instance of the class. Below is an example and that’s how scala implements object at backend.
class Singleton {
public static final Singleton INSTANCE = new Singleton();
private Singleton() {}
}
Imagine we have a Test object in file Test.scala. Compile it with scalac and check the class files with javap.
object Test {
def hi(): Unit = {}
}
2 class files are generated. One is the Test class. Test$ is the singleton class.
When you call Test.hi(), actually you are using the singleton instance MODULE$ and call its hi() method. That’s so called static forwarder. You wound’t be willing to use something like Test$.MODULE$.hi() literally, no one will dive into the byte code for method calling 🙂.
Let’s also check the compiled code with JD-GUI. Look at the Test$.class, exactly same with the java singleton implementation above!