开发者

Relationship between this and this.type

The following:

trait Foo {
    type T
    val foo: T
}

trait Bar extends Foo {
    type T = this.type
    val foo = this
}

gives the compiler error:

<console>:8: error: overriding value foo in trait Foo of type Bar.this.T;
 value foo has incompatible type
        val foo = this
            ^

However, if I change the last line to:

val foo: this.type = this

it compiles without error.

Why do I have to 开发者_运维技巧specify the type explicitly here? I've already said the the type of foo should be T and that T should be this.type. Is the type of this not this.type?


The Scala compiler never automatically infers singleton types like this.type. They are somehow “too specific” and would lead to strange behaviors in other more common situations.

On the same topic, see also:

  • 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜