Singletons as Synthetic classes in Scala?

后端 未结 2 1348
说谎
说谎 2020-12-06 00:27

I am reading Programming in Scala, and I don\'t understand the following sentence (pdf p.112):

Each singleton object is implemented as an instance of

2条回答
  •  忘掉有多难
    2020-12-06 01:01

    The chapter 31 of the same "Programming in Scala" is more precise:

    Java has no exact equivalent to a singleton object, but it does have static methods.

    The Scala translation of singleton objects uses a combination of static and instance methods. For every Scala singleton object, the compiler will create a Java class for the object with a dollar sign added to the end.
    For a singleton object named App, the compiler produces a Java class named App$.
    This class has all the methods and fields of the Scala singleton object.
    The Java class also has a single static field named MODULE$ to hold the one instance of the class that is created at run time.
    As a full example, suppose you compile the following singleton object:

    object App {
      def main(args: Array[String]) {
        println("Hello, world!")
      }
    }
    

    Scala will generate a Java App$ class with the following fields and methods:

    $ javap App$
    public final class App$ extends java.lang.Object
        implements scala.ScalaObject{
      public static final App$ MODULE$;
      public static {};
      public App$();
      public void main(java.lang.String[]);
      public int $tag();
    }
    

    That’s the translation for the general case.

提交回复
热议问题