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 reflection API?
I know that one difference is that the class name of a singleton object ends with a $
, but this is not a strict way.
So, simply call the method which is returning your expected singleton type of object and call hashcode() method on it. If it prints the same hashcode each time, it means it's singleton, else it's not.
Instead of static keyword Scala has singleton object. A Singleton object is an object which defines a single object of a class. A singleton object provides an entry point to your program execution. If you do not create a singleton object in your program, then your code compile successfully but does not give output.
Singleton object is an object which is declared by using object keyword instead by class. No object is required to call methods declared inside singleton object. In scala, there is no static concept. So scala creates a singleton object to provide entry point for your program execution.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With