Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do self: T => and this: T => have the same meaning when defining a trait?

Tags:

scala

traits

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?

like image 434
huynhjl Avatar asked Feb 08 '10 01:02

huynhjl


People also ask

What is a self type?

Self-types are a way to declare that a trait must be mixed into another trait, even though it doesn't directly extend it. That makes the members of the dependency available without imports. A self-type is a way to narrow the type of this or another identifier that aliases this .

How do you use traits in Scala?

In scala, trait is a collection of abstract and non-abstract methods. You can create trait that can have all abstract methods or some abstract and some non-abstract methods. A variable that is declared either by using val or var keyword in a trait get internally implemented in the class that implements the trait.


2 Answers

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.

like image 67
Miles Sabin Avatar answered Nov 05 '22 08:11

Miles Sabin


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)
}
like image 6
Mitch Blevins Avatar answered Nov 05 '22 08:11

Mitch Blevins