Scala 为什么[A.type]的类不编译?

Scala 为什么[A.type]的类不编译?,scala,singleton-type,Scala,Singleton Type,签名是 因此,使用 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

签名是

因此,使用

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    

你只能得到某个类的类标签,
Foo.type
不是类。-请注意,这里我们讨论的是编译器对类的理解,当然在JVM am对象中,在运行时有一个底层类,但对于语言规范来说,对象不是类。实际上它在2.13.4及以后版本中编译。因此=2.13.4它被认为是有类的?即使在2.13.4之前,您仍然可以执行
Foo.getClass
。您可以通过
classOf
和链接的票证阅读有关更改的信息。@Luis我认为这实际上更像是一个实现细节。但显然,有些用例需要
classOf[Foo.type]
才能工作(即需要文本作为输入的注释)。我认为这是语言的一部分,尽管
objectfoo
定义了一个新类,它正好有一个实例。但是这个类是什么以及它是如何工作的是一个实现细节。
val foo: Foo.type = Foo

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