Scala's .type and Java's .class literal

前端 未结 2 1916
遇见更好的自我
遇见更好的自我 2021-01-31 16:49

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

2条回答
  •  臣服心动
    2021-01-31 17:04

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

提交回复
热议问题