一个规则是 Scala 从不推断单例类型this.type。例如首先考虑它的机制
scala> trait Foo {
| type T
| def f() = this // we left out the return type to see what Scala will infer
| }
// defined trait Foo
scala> new Foo { type T = String }
val res0: Foo{T = String} = anon$1@6d3ad37a
scala> res0.f()
val res1: Foo = anon$1@6d3ad37a
注意res1 的返回类型是Foo 而不是Foo { type T = String },所以我们丢失了一些类型信息
scala> val x: res1.T = ""
1 |val x: res1.T = ""
| ^^
| Found: ("" : String)
| Required: res1.T
注意编译器不知道res1.T实际上是一个String。所以编译器没有推断出单例类型this.type,它包含所有类型信息,包括T被实例化为的类型成员
scala> trait Foo {
| type T
| def f(): this.type = this
| }
// defined trait Foo
scala> new Foo { type T = String }
val res2: Foo{T = String} = anon$1@7d381eae
scala> res2.f()
val res3: Foo{T = String} = anon$1@7d381eae
scala> val x: res3.T = ""
val x: res3.T = ""
注意在我们显式声明单例返回类型this.type 后,编译器如何知道T 是String。
这是另一个机械示例,说明编译器不推断单例类型this.type
scala> trait Foo {
| def f() = this // let inference do its thing
| }
// defined trait Foo
scala> trait Bar {
| def g() = 42
| }
// defined trait Bar
scala> trait Bar extends Foo {
| def g(): Int = 42
| }
// defined trait Bar
scala> new Bar {}
val res5: Bar = anon$1@6a9a6a0c
scala> res5.f()
val res6: Foo = anon$1@6a9a6a0c
scala> res6.g()
1 |res6.g()
|^^^^^^
|value g is not a member of Foo
注意f() 调用是如何输入到Foo 的,而Bar 可能不是预期的。另一方面,如果我们提供显式的单例返回类型this.type 那么
scala> trait Foo {
| def f(): this.type = this
| }
// defined trait Foo
scala> trait Bar extends Foo {
| def g(): Int = 42
| }
// defined trait Bar
scala> new Bar {}
val res7: Bar = anon$1@4707d60a
scala> res7.f()
val res8: Bar = anon$1@4707d60a
scala> res8.g()
val res9: Int = 42
我们看到f() 呼叫键入到Bar。
这些是机制,但实际应用呢?我知道的两种用途是: