I wonder from a language design perspective why Scala has removed Java\'s class literal (e. g. String.class
) and replaced it with classOf[String]
, but
Actually, it is quite consistent. Singleton.type
is a dependent type of Singleton
, while classOf[Class]
is a type parameter to a method.
Consider this:
class A {
class B
}
val a: A = new A
val b: a.B = new a.B
The point here is that .
is used to indicate something that is a member of a value. It may be a val
, a var
, a def
or an object
and it may also be a type
, a class
or a trait
.
Since a singleton object is a value, then Singleton.type
is perfectly valid.
On the other hand, a class is not an object, so Class.class
doesn't make sense. Class
doesn't exist (as a value), so it is not possible to get a member of it. On the other hand, it's definition as def classOf[T]: Class[T]
is plain Scala code (even if the actual implementation is compiler magic).