scala Scala中单例对象的解释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6541393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:09:02  来源:igfitidea点击:

Explanation of singleton objects in Scala

scalasingleton

提问by gks

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.

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

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

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

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

我正在阅读《Scala 编程》一书,第 4 章刚刚谈到了单例对象,但并没有详细说明为什么这很重要。

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.

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

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

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

回答by Kevin Wright

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

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

(indeed, companion object methods are exposed via "static forwarders" for the sake of Java interop)

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

However, singletons go a fair way beyond this.

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

  • A singleton can inherit methods from other classes/traits, which can't be done with statics.
  • A singleton can be passed as a parameter (perhaps via an inherited interface)
  • A singleton can exist within the scope of a surrounding class or method, just as Java can have inner classes
  • It's also worth noting that a singleton doesn't have to be a companion, it's perfectly valid to define a singleton without also defining a companion class.
  • 单例可以从其他类/特征继承方法,这是静态无法完成的。
  • 单例可以作为参数传递(可能通过继承的接口)
  • 单例可以存在于周围的类或方法的范围内,就像 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 成为一种比 Java 更面向对象的语言(静态方法不属于对象)。具有讽刺意味的是,它主要是根据其功能凭据进行讨论的。

回答by jilen

In many cases we need a singleton to stand for unique object in our software system. Think about the the solar system. We may have following classes

在许多情况下,我们需要一个单例来代表我们软件系统中的唯一对象。想想太阳系。我们可能有以下课程

class Planet
object Earth extends Planet
object Sun extends Planet

object is a simple way to create singleton, of course it is usually used to create class level method, as static method in java

object 是一种创建单例的简单方法,当然它通常用于创建类级别的方法,如java中的静态方法

回答by Landei

Additional to the given answers (and going in the same general direction as jilen), objects play an important role in Scala's implicitmechanism, e.g. allowing type-class-like behavior (as known from Haskell):

除了给定的答案(并与 jilen 朝着相同的总体方向发展)之外,objects 在 Scala 的implicit机制中发挥着重要作用,例如允许类类行为(如 Haskell 所知):

trait Monoid[T] {
  def zero:T
  def sum(t1:T, t2:T):T
}

def fold[T](ts:T*)(implicit m:Monoid[T]) = ts.foldLeft(m.zero)(m.sum(_,_))

Now we have a fold-Function. which "collapses" a number of Ts together, as long as there is an appropriate Monoid(things that have a neutral element, and can be "added" somehow together) for T. In order to use this, we need only oneinstance of a Monoidfor some type T, the perfect job for an object:

现在我们有一个fold-Function。其中“崩溃”的数的T小号一起,只要有适当的Monoid(东西具有中性元素,并且可以“加入”以某种方式一起)对T。为了使用它,我们只需要一个 a 的实例来Monoid表示某种类型T,这对 an 来说是完美的工作object

implicit object StringMonoid extends Monoid[String] {
  def zero = ""
  def sum(s1:String, s2:String) = s1 + s2
}

Now this works:

现在这有效:

println(fold("a","bc","def"))  //--> abcdef

So objects are very useful in their own right.

所以objects 本身就非常有用。

But wait, there is more!Companion objects can also serve as a kind of "default configuration" when extending their companion class:

但是等等,还有更多!当扩展它们的伴生类时,伴生对象也可以作为一种“默认配置”:

trait Config {
  def databaseName:String
  def userName:String
  def password:String
}

object Config extends Config {
  def databaseName = "testDB"
  def userName = "scott"
  def password = "tiger"
}

So on the one hand you have the trait Config, which can be implemented by the user however she wants, but on the other hand there is a ready made object Configwhen you want to go with the default settings.

因此,一方面您拥有 trait Config,它可以由用户实现,但她想要,但另一方面,Config当您想要使用默认设置时,有一个现成的对象。

回答by Casual Jim

Yes, it is basically a way of providing class methodswhen used as a companion object.

是的,当用作伴生对象时,它基本上是提供类方法的一种方式。