以下内容:
trait Foo {
type T
val foo: T
}
trait Bar extends Foo {
type T = this.type
val foo = this
}
给出编译器错误:
<console>:8: error: overriding value foo in trait Foo of type Bar.this.T;
value foo has incompatible type
val foo = this
^
但是,如果我将最后一行更改为:
val foo: this.type = this
编译没有错误。
为什么我必须在这里明确指定类型?我已经说过 foo
的类型应该是 T
并且 T
应该是 this.type
。 this
的类型不是 this.type
吗?
最佳答案
Scala 编译器永远不会自动推断单例类型,如 this.type
。它们在某种程度上“过于具体”,会在其他更常见的情况下导致奇怪的行为。
关于同一主题,另请参阅:
- Scala this.type conformance to type parameter bounds of supertype
- Defining a method whose return type is the singleton type of an argument of that method
- Scala abstract type representing type of subclass
- Driving a singleton type through a brickwall
- How to correctly type-annotate this HList?
- Singleton types are mean and spiteful
关于scala - this 和 this.type 之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6958668/