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 nothin开发者_Python百科g worked.
(I know of course about getClass
, the runtime version of classOf
, but that's not what I'm asking.)
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
精彩评论