Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In scala, is there any way to check if an instance is a singleton object or not?

Tags:

scala

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.

like image 429
SleePy Avatar asked Mar 15 '16 17:03

SleePy


People also ask

How do you find whether the object is singleton or not?

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.

Is object in Scala singleton?

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.

What is singleton object in Scala with example?

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.


1 Answers

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.

like image 186
Travis Brown Avatar answered Sep 23 '22 10:09

Travis Brown