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 has then added a "type literal" with its Singletons like Singleton.type
instead of something like typeOf[Singleton]
?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Here is my rationalization:
classOf[T]
classOf
is defined inPredef
as a function with this signature:Although it's implemented by the compiler, using the function syntax is possible without having to create any special treatment in terms of syntax. So that's one reason here to consider this option.
The alternative like
String.class
would imply that each class has a companion object with a fieldclass
. So there are two problems:class
is a keyword, so that causes a problem where the syntax would require a special case for itclass A
without a companion object, it's would be odd to be able to refer toA.class
, which would be like accessing the class field on the companionA
.A.type:
On why
typeOf[A]
may be confusing. It looks like a function call, but types don't live in the same world as function results (function results have types, but the type itself only makes sense at compile time). I can ascribe a type to a variable:I can't assign a type like it's returned by a function:
On the other hand types can be member of a object:
So it is not a big stretch to have
A.type
refer to the type of objectA
. Note that.type
aren't used beyond referring to types of singleton objects, so it's not really that frequent.Actually, it is quite consistent.
Singleton.type
is a dependent type ofSingleton
, whileclassOf[Class]
is a type parameter to a method.Consider this:
The point here is that
.
is used to indicate something that is a member of a value. It may be aval
, avar
, adef
or anobject
and it may also be atype
, aclass
or atrait
.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 asdef classOf[T]: Class[T]
is plain Scala code (even if the actual implementation is compiler magic).