Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the class of a singleton object at compile time?

Consider something like this:

object Singleton

val cls: Class[Singleton] = ???

What do I have to write instead of ????

I tried classOf[Singleton], classOf[Singleton.type], Singleton.type, but nothing worked.

(I know of course about getClass, the runtime version of classOf, but that's not what I'm asking.)

like image 980
soc Avatar asked May 24 '11 23:05

soc


People also ask

How do you identify a singleton class?

We can distinguish a Singleton class from the usual classes with respect to the process of instantiating the object of the class. To instantiate a normal class, we use a java constructor. On the other hand, to instantiate a singleton class, we use the getInstance() method.

What is the most common method signature to obtain a singleton?

The most popular approach is to implement a Singleton by creating a regular class and making sure it has: A private constructor. A static field containing its only instance. A static factory method for obtaining the instance.

Can we inherit a singleton class?

Unlike static classes, Singleton classes can be inherited, can have base class, can be serialized and can implement interfaces.

How many instances can a singleton class have at a time?

The Singleton is a useful Design Pattern for allowing only one instance of your class, but common mistakes can inadvertently allow more than one instance to be created.


2 Answers

Here a solution, but it's not pretty ...

object Singleton

val cls : Class[Singleton] = Singleton.getClass.asInstanceOf[Class[Singleton]]

Edit: completed the solution after reading another question/answer: Scala equivalent of Java java.lang.Class<T> Object

Note1: type erasure would prevent this from being particularly useful, e.g. in pattern matching. See referenced question/answer, above, for a good explanation

Note2: the scala -explaintypes flag is quite handy in understanding type errors.

HTH

like image 60
laher Avatar answered Oct 19 '22 21:10

laher


You are not alone with this problem. The answer is: There is currently no way to avoid a Singleton.getClass. See this comment for more information why classOf[Singleton] does not work

like image 37
kiritsuku Avatar answered Oct 19 '22 23:10

kiritsuku