If I have an instance of an object, is there a way to check if I have a singleton object rather than an instance of a class? Is there any method can do this? May be some reflect
Yep, using the little-documented scala.Singleton
type:
def isSingleton[A](a: A)(implicit ev: A <:< Singleton = null) =
Option(ev).isDefined
And then:
scala> val X = new Foo(10)
X: Foo = Foo@3d5c818f
scala> object Y extends Foo(11)
defined object Y
scala> isSingleton(X)
res0: Boolean = false
scala> isSingleton(Y)
res1: Boolean = true
My isSingleton
method is just a demonstration that provides a runtime boolean value that tells you whether or not an expression is statically typed as a singleton type, but you can also use Singleton
as evidence at compile time that a type is a singleton type.