为什么 classOf[A.type] 不能编译?

时间:2021-02-15 18:02:23

标签: scala singleton-type

Predef.classOf 的签名是

def classOf[T]: Class[T]

所以模仿上面的签名

object Foo
def f[T]: Class[T] = null

为什么下面会编译

f[Foo.type]         // ok

但在 Scala 中出现以下错误

classOf[Foo.type]   // error: class type required but Foo.type found

编辑:在 Scala 2.13.4 及以后的版本中,上述确实有效(如评论中所指出的),但是在以下情况下仍然会发生类似的编译时错误

val foo: Foo.type = Foo

f[foo.type]         // ok              
classOf[foo.type]   // error: class type required but foo.type found    

0 个答案:

没有答案