Search code examples
scalasyntaxself-type

What's the difference between self-type `this: T =>` and `this: T`?


Between Scala (2.12.8) self-type

trait T {
   this: Any =>
}

and this

trait T {
   this: Any
}

what's the semantics difference?

In other words, what is the purpose of this: Any (in the second snippet)?

I expected the compiler to yell I should not declare this when compiling the second code snippet, but I get this warning instead:

Warning:(2, 9) a pure expression does nothing in statement position
multiline expressions may require enclosing parentheses
    this: Any

Solution

  • The keyword this is an expression of type T. T is subtype of Any, because everything is subtype of Any. Hence you can explicitly ascribe type Any to the expression this. It is valid to have expressions in the initializer, so you can write the expression this: Any in the body of T.

    You might as well have written

    trait T { 42: Int }
    

    or

    trait T { ((((this: T): T): T): T): Any }
    

    In both cases, 42 and this would be just expressions with explicit type ascription that simply don't do anything. They are not declarations, and they have nothing to do with the self type.