10

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

soc
  • 27,983
  • 20
  • 111
  • 215

2 Answers2

7

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

Community
  • 1
  • 1
laher
  • 8,860
  • 3
  • 29
  • 39
4

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

kiritsuku
  • 52,967
  • 18
  • 114
  • 136