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.)
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.
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.
Unlike static classes, Singleton classes can be inherited, can have base class, can be serialized and can implement interfaces.
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.
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
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
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