Scala中单例对象的解释

Scala中单例对象的解释

本文介绍了Scala中单例对象的解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到的编码是你基本上提供了一个对象 SomeClass"和一个类 SomeClass",伴随类是类声明,对象是一个 单身.其中不能创建实例.所以......我的问题主要是在这个特定实例中单例对象的目的.

I get the coding in that you basically provide an "object SomeClass" and a "class SomeClass" and the companion class is the class declaration and the object is a singleton. Of which you cannot create an instance. So... my question is mostly the purpose of a singleton object in this particular instance.

这基本上只是在 Scala 中提供类方法的一种方式吗?喜欢 Objective-C 中基于 + 的方法吗?

Is this basically just a way to provide class methods in Scala? Like + based methods in Objective-C?

我正在阅读 Scala 编程本书和第 4 章只讨论了单例对象,但没有详细说明为什么这很重要.

I'm reading the Programming in Scala book and Chapter 4 just talked about singleton objects, but it doesn't get into a lot of detail on why this matters.

我意识到我在这里可能会超前,稍后可能会更详细地解释.如果是这样,请告诉我.到目前为止,这本书还算不错,但它有很多在 Java 中,你可以这样做"的内容,但我的 Java 经验太少,以至于我有点错过了我担心的一点.我不希望这是其中一种情况.

I realize I may be getting ahead of myself here and that it might be explained in greater detail later. If so, let me know. This book is reasonably good so far, but it has a lot of "in Java, you do this", but I have so little Java experience that I sort of miss a bit of the points I fear. I don't want this to be one of those situations.

我不记得在 Scala 编程网站上的任何地方阅读过Java 是阅读本书的先决条件...

I don't recall reading anywhere on the Programming in Scala website that Java was a prerequisite for reading this book...

推荐答案

是的,配套单例提供了与 Java(以及 C++、c# 等)静态方法等效的方法.

Yes, companion singletons provide an equivalent to Java's (and C++'s, c#'s, etc.) static methods.

(实际上,为了 Java 互操作,伴随对象方法通过静态转发器"公开)

然而,单身人士远远不止于此.

However, singletons go a fair way beyond this.

  • 单例可以从其他类/特征继承方法,而静态无法做到这一点.
  • 单例可以作为参数传递(可能通过继承的接口)
  • 单例可以存在于周围的类或方法的范围内,就像 Java 可以有内部类一样
  • 还值得注意的是,单例不一定是伴随类,定义单例而不定义伴随类是完全有效的.

这有助于使 Scala 成为一种远比 Java 更面向对象的语言(静态方法不属于对象).具有讽刺意味的是,它主要是根据其功能凭据进行讨论的.

Which helps make Scala a far more object-oriented language that Java (static methods don't belong to an object). Ironic, given that it's largely discussed in terms of its functional credentials.

这篇关于Scala中单例对象的解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 08:08