单例类型中的表面不一致

mis*_*tor 6 types type-systems programming-languages scala singleton-type

我有几个关于单例类型的问题,但由于它们都非常密切相关,我将它们发布在同一个线程下.

Q1.为什么#1不编译但#2呢?

def id(x: Any): x.type = x      // #1
def id(x: AnyRef): x.type = x   // #2
Run Code Online (Sandbox Code Playgroud)

Q2.在String我尝试的其他引用类型的情况下,正确推断出类型.为什么会这样?

scala> id("hello")
res3: String = hello

scala> id(BigInt(9))
res4: AnyRef = 9

scala> class Foo
defined class Foo

scala> id(new Foo)
res5: AnyRef = Foo@7c5c5601
Run Code Online (Sandbox Code Playgroud)

ret*_*nym 7

单例类型只能引用AnyRef后代.有关更多详细信息,请参阅为什么字符串文字符合Scala Singleton.

应用程序id(BigInt(9))无法通过稳定路径引用的参数,因此没有一个有趣的单例类型.

scala> id(new {})
res4: AnyRef = $anon$1@7440d1b0

scala> var o = new {}; id(o)
o: Object = $anon$1@68207d99
res5: AnyRef = $anon$1@68207d99

scala> def o = new {}; id(o)
o: Object
res6: AnyRef = $anon$1@2d76343e

scala> val o = new {}; id(o) // Third time's the charm!
o: Object = $anon$1@3806846c
res7: o.type = $anon$1@3806846c
Run Code Online (Sandbox Code Playgroud)