In Scala, I've seen the constructs
trait T extends S
and
trait T { this: S =>
used to achieve similar things (namely that the abstract methods in S
must be defined before an instance may be created). What's the difference between them? Why would you use one over the other?
It lets you create dependencies among modules. For instance: class System extends Base with CompA with CompB with CompC. If CompA needs to use something from CompC , it can be defined as: trait CompA { self: CompC => ... } In this case: class System extends Base with CompA with CompB.
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 .
Trait supports multiple inheritance. Abstract Class supports single inheritance only. Trait can be added to an object instance. Abstract class cannot be added to an object instance.
A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Unlike class inheritance, in which each class must inherit from just one superclass, a class can mix in any number of traits.
Self type annotations allow you to express cyclic dependencies. For instance:
trait A extends B trait B { self: A => }
This is not possible with simple inheritance.
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