Search code examples
classscalaprogramming-languagessingletonlanguage-design

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.)


Solution

  • 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