单例作为 Scala 中的合成类? [英] Singletons as Synthetic classes in Scala?
问题描述
我正在阅读 Scala 编程,但我不明白以下句子 (pdf p.112):
<块引用>每个单例对象都被实现为一个合成类的实例,该类引用自静态变量,因此它们具有与 Java 静态变量相同的初始化语义.
这是否意味着如果我在 Scala 中有一个单例 FooBar,编译器会创建一个名为 FooBar$ 的类?
还有作者所说的从静态变量引用"是什么意思?是否有一个隐藏的静态变量保存对某个 FooBar$ 类的引用?
感谢您的帮助.
同《Programming in Scala》的第 31 章更精确:
<块引用>Java 没有完全等同于单例对象,但它确实有静态方法.
单例对象的 Scala 翻译使用静态和实例方法的组合.对于每个 Scala 单例对象,编译器都会为该对象创建一个 Java 类,并在末尾添加一个美元符号.
对于名为 App
的单例对象,编译器会生成一个名为 App$
的 Java 类.
这个类拥有 Scala 单例对象的所有方法和字段.
Java 类还有一个名为 MODULE$
的静态字段来保存在运行时创建的类的实例.
作为一个完整的示例,假设您编译以下单例对象:
object App {def main(args: Array[String]) {println("你好,世界!")}}
<块引用>
Scala 将生成具有以下字段和方法的 Java App$ 类:
$ javap App$公共最终类 App$ 扩展 java.lang.Object实现 scala.ScalaObject{public static final App$ MODULE$;公共静态{};公共应用$();public void main(java.lang.String[]);公共 int $tag();}
<块引用>
这是一般情况的翻译.
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 a synthetic class referenced from a static variable, so they have the same initialization semantics as Java statics.
Does this mean the if I have a singleton FooBar in scala, the compiler will create a class named FooBar$?
Also what does the author mean by "referenced from a static variable"? Is there a hidden static variable somewhere holding a reference to some FooBar$ class?
I appreciate any help here.
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 namedApp
, the compiler produces a Java class namedApp$
.
This class has all the methods and fields of the Scala singleton object.
The Java class also has a single static field namedMODULE$
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.
这篇关于单例作为 Scala 中的合成类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!