Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there are two class files generated after compiling scala code?

Tags:

scala

When we compile scala code using

scalac code.scala

There are two files created named code.class and code$.class. What is the purpose of this second file?

For reference,

object HelloWorld {
    def main (args: Array[String]) {
        println ("Hello world! This is my first scala program!");
    }
}

This is the code inside code.scala file.

like image 301
Fahad Siddiqui Avatar asked Feb 09 '23 21:02

Fahad Siddiqui


1 Answers

This is the consequence of how Scala translates the Scala object to JVM constructs. An object X is translated to a class X$ with ordinary methods, ordinary inheritance etc.

As object X creates singleton in Scala, it would be nice to be able to access its public methods from Java by calling them as static methods X.someMethod(). That is why the Scala compiler creates also a class X with static methods calling the ordinary methods of the singleton instance of the class X$. Even if you don't have the Scala class X itself.

like image 119
Gregor Raýman Avatar answered Feb 16 '23 02:02

Gregor Raýman