Reputation: 363
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. However I am able to create two different objects of type A
using following piece of code.
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?
Upvotes: 2
Views: 799
Reputation: 4595
An object
by itself is a singleton. 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
. 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.
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.
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. Again, A.type
could be a subtype of A
if you explicitly make it so.
Upvotes: 4
Reputation: 51271
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
Upvotes: 4
Reputation: 170919
new A
refers to class A
(which is not a singleton), not to object A
. You can easily check it: if you remove class A
, the new A
lines will no longer compile.
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.
Upvotes: 0
Reputation: 1016
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
Upvotes: 0