简体   繁体   English

Scala伴侣对象不是单例

[英]Scala companion objects are not singleton

I have following two classes. 我有以下两节课。

class A (name: String) {
}

object A {
}

According to definition of Singleton, we can have only one object of that type. 根据Singleton的定义,我们只能具有该类型的一个对象。 However I am able to create two different objects of type A using following piece of code. 但是,我可以使用下面的代码创建两个不同的A型对象。

object B {
   def main(args: Array[String]): Unit = {
     val a = new A("Vinod")
     println(a)

     val b = new A("XYZ")
     println(b)
  }
}

can someone please explain me, where my understanding is not correct? 有人可以解释我的理解不正确吗?

The companion object is not an instance of the companion class. 伴随对象不是伴随类的实例。 They're not even the same type. 它们甚至不是同一类型。

class A
object A {
  var state = 0
  def update() :Unit = state = state + 1
}

val abc :A = new A   //instance of class A
val xyz :A.type = A  //2nd reference to object A

// both reference the same singleton object
xyz.update()  //res0: Unit = ()
A.state       //res1: Int = 1
abc.state     //Error: value state is not a member of A$A2521.this.A

An object by itself is a singleton. 一个object本身就是一个单例。 It has its own class and no other instance of the same class exist at runtime. 它具有自己的类,并且在运行时不存在同一类的其他实例。

However, the pattern you describe here is different: object A is not an instance of class A unless you make it so using object A extends A . 但是,这里描述的模式是不同的: object A 不是A的实例,除非您使用object A extends A You could make it the only instance of class A by making class A a sealed class, but this is unnecessary in almost all cases. 通过将Asealed类,可以使其成为A类的唯一实例,但这在几乎所有情况下都是不必要的。

If you really want the singleton pattern, drop the class and use only object A , all of its members will be "static" in the sense of Java. 如果您确实需要单例模式,则删除class并仅使用object A ,就Java而言,其所有成员都是“静态的”。

Note that the actual type of object A can be referred to as A.type , which by default is completely unrelated to type A if class A exists. 请注意, object A的实际类型可以称为A.type ,如果存在类A ,则默认情况下它与类型A完全无关。 Again, A.type could be a subtype of A if you explicitly make it so. 再次, A.type 可能的子类型A ,如果你明确的是真的。

the companion object can be thought of as the static space of a class. 伴随对象可以被视为类的静态空间。 if you want to make A a singleton you can make it an object rather than a class 如果您想使A为单身人士,则可以使其成为对象而不是类

new A refers to class A (which is not a singleton), not to object A . new A引用class A (不是单例),而不是object A You can easily check it: if you remove class A , the new A lines will no longer compile. 您可以轻松地检查它:如果删除class A ,则new A行将不再编译。

Also note that object s aren't necessarily singletons: they can be nested inside classes or traits, in this case there is one for each instance of the outer type. 还要注意, object 不一定是单例的:它们可以嵌套在类或特征内,在这种情况下,外部类型的每个实例都有一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM