Knut Arne Vedaa
Knut Arne Vedaa

Reputation: 15742

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?

Upvotes: 2

Views: 192

Answers (1)

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 59994

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:

Upvotes: 6

Related Questions