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?
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 .
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.
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With