Scala Trait self-types or "How do I tell my trait where it's going to be mixed in?"


A feature of Scala whose syntax I tend to forget are self-types, with which you can tell a trait where it is going to be mixed in, just like this:

class Foo {
    def x = 5
}

trait Bar { self: Foo =>
    def y = x + 10
}

The self: Foo => part tells the trait that it is going to be mixed into a class of type Foo and that it can therefore use all methods from this type. This is why the Bar trait is then able to call the x method from the Foo class:

scala> (new Foo with Bar).y
res4: Int = 15

Whereas the following will fail miserably:

scala> (new Object with Bar).y
:10: error: illegal inheritance;
  self-type java.lang.Object with Bar does not conform to Bar's selftype Bar with Foo
          (new Object with Bar).y