Scala:Singleton对象与匿名类
在Scala中,内部单例对象和一个匿名的内部类似乎达到了相同的目的。它们之间有什么区别,我何时应该更喜欢使用另一个?
内列顿对象:
object Main extends App {
object A {
val a = 7
}
println(A.a)
}
匿名内部类:
object Main extends App {
val A = new {
val a = 7
}
println(A.a)
}
In Scala, an inner singleton object and an anonymous inner class seem to achieve the same end. What are the differences between them, and when should I prefer using one over the other?
Inner singleton object:
object Main extends App {
object A {
val a = 7
}
println(A.a)
}
Anonymous inner class:
object Main extends App {
val A = new {
val a = 7
}
println(A.a)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
他们之间有一个明显的区别,我将解释:
此描述直接从 scala 4th ed。摘要Vals)M。Odersky,B。Venners和L.Spoon。
这是一个示例,显示了差异:
输出:
在实例化匿名类时,您可以看到。
val a
在初始化参考a
之前评估。与Demo
不一样。val a
仅在对象demo
首先使用的情况下初始化,这是打印它的行,而不是定义的位置。当要在功能更大的和/或更有效的内存方面代码时,应使用对象。由于对物体进行了懒惰的评估,因此如果需要时,它们会在需要时准确评估。如果不需要它们,则不会对其进行评估。因此,您可以避免在那里的内存开销,例如,如果对匿名类的评估是计算密集型操作,那么如果您在企业应用程序中使用了很多,这可能会有所作为。
There is one visible difference between them and I shall explain:
This description is taken directly from Programming in Scala 4th Ed. (Chapter 20. Abstract Members. Subchapter 20.5 Initializing abstract vals) by M. Odersky, B. Venners and L. Spoon.
Here is an example, that shows the difference:
Output:
As you can see, when you instantiate an anonymous class.
Val a
is evaluated before the referenceA
is initialized. That is not the same withDemo
.Val a
is only initialized where the objectDemo
is first used, and that is the line that prints it, not where it is defined.You should use objects when you want to code in a more functional and/or be more efficient in terms of memory. Because objects are lazy evaluated, they get evaluated exactly when they are needed, if they are needed. If they aren't needed, they will not be evaluated. So you avoid a memory overhead right there, for example if the evaluation of the anonymous class is an compute-intensive operation, this can make a difference if you use a lot of them in an enterprise application.