Java 中 Scala 对象的等价物是什么?
在Scala中,我们可以写
object Foo { def bar = {} }
编译器是如何实现的?我可以从 Java 调用 Foo.bar();
但是 Java 中的 new Foo(); 给出错误 cannot find symbol symbol: constructor Foo()
- JVM 本身是否支持单例?
- Java中是否可以有一个没有构造函数的类?
注意:这里是 scalac -print 输出的代码
package <empty> {
final class Foo extends java.lang.Object with ScalaObject {
def bar(): Unit = ();
def this(): object Foo = {
Foo.super.this();
()
}
}
}
In Scala, we can write
object Foo { def bar = {} }
How is this implemented by the compiler? I am able to call Foo.bar();
from Java
but new Foo();
from Java gives the error cannot find symbol symbol: constructor Foo()
- Does the JVM support singletons natively?
- Is it possible to have a class in Java that does not have a constructor?
Note: here is the code output by scalac -print
package <empty> {
final class Foo extends java.lang.Object with ScalaObject {
def bar(): Unit = ();
def this(): object Foo = {
Foo.super.this();
()
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编译代码时,Scala 编译器会生成与以下 Java 代码等效的代码:
这里
Foo$
是单例的实际实现,而Foo
提供static< /code> 与 Java 交互的方法。
When compiling your code, Scala compiler produces an equivalent of the following Java code:
Here
Foo$
is an actual implementation of a singleton, whereasFoo
provides astatic
method for interaction with Java.对单例的支持不是在语言级别上,但是该语言提供了足够的设施来毫无困难地创建它们。
考虑以下代码:
这是来自维基百科的示例,它解释了如何创建单例。实例保存在私有字段中,构造函数在类外部无法访问,该方法返回此单个实例。
至于构造函数:默认情况下,每个类都有一个所谓的默认构造函数,它不带参数,只是调用超类的无参数构造函数。如果超类没有任何可访问的无参数构造函数,则必须编写显式构造函数。
因此,一个类必须有一个构造函数,但如果超类有一个无参数构造函数,则不必编写它。
Support for singletons is not on a language level, but the language provides enough facilities to create them without any trouble.
Consider the following code:
This is an example from Wikipedia, which explains how a singleton can be made. An instance is kept in a private field, constructor is inaccessible outside the class, the method returns this single instance.
As for constructors: every class by default has a so-called default constructor which takes no arguments and simply calls the no-args constructor of the superclass. If the superclass doesn't have any accessible constructor without arguments, you will have to write an explicit constructor.
So a class must have a constructor, but you don't have to write it if the superclass has a no-args constructor.
Joshua Bloch 在《Effective Java》一书中推荐使用枚举来实现单例。
看这个问题:
在 Java 中实现单例模式的有效方法是什么?
Joshua Bloch recommened in the book "Effective Java" the use of an enum to implement a singleton.
See this question:
What is an efficient way to implement a singleton pattern in Java?