tags:

views:

170

answers:

2

It seems I can use self or this for referring to the mixed-in instance or rather to constraint the mixed-in instance. For instance, are those equivalent?

scala> trait A { self: List[_] => }
defined trait A

scala> trait B { this: List[_] => }
defined trait B

Is this just a convention, or using something different than this provide some benefits?

+5  A: 

It can be anything: self, this, meep, blah, etc. It is used only by the compiler in determining which class to cast to (when calling methods on it) and does not actually show up in the bytecode.

Take care when naming, because local identifiers override the self type definition:

trait A {
  def baz = println("baz!")
}
trait B {
  foo: A => 
  val foo = "hello"   
  // def bar = foo.baz // does not compile because foo is String, not A
  def bar = foo.substring(1)
}
Mitch Blevins
+6  A: 

Using a name other than "this" can be useful where you have member types which refer to the enclosing instance. For example,

trait Outer { self =>
  trait Inner {
    def outer = self
  }
}

is preferable to,

trait Outer {
  trait Inner {
    def outer = Outer.this
  }
}

in some circumstances.

Miles Sabin