Reputation: 15435
Is there a way to do an asInstanceOf
on a Scala object
. Even though it is a singleton, it is still an instance. So why can't I do an asInstanceOf
on this singleton?
Say:
case object MyObject
Upvotes: 2
Views: 221
Reputation: 22105
You can, actually:
$ scala
Welcome to Scala version 2.10.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_39).
Type in expressions to have them evaluated.
Type :help for more information.
scala> case object MyObject
defined module MyObject
scala> val x: Any = MyObject
x: Any = MyObject
scala> x.asInstanceOf[MyObject.type]
res0: MyObject.type = MyObject
Upvotes: 3
Reputation: 20435
By definition a singleton (namely a Scala object) has one only instance, referred by the name used in the object declaration.
Also note that in a class you can refer to the type by the class name itself,
case class B()
val b = B()
b.isInstanceOf[B]
res: Boolean = true
However a case object
proves to be a single instance; to refer to its type consider
case object A
A.isInstanceOf[A.type]
res: Boolean = true
Upvotes: 0