Self-type annotations/references allow us to redefine the this
pointer and provide a way to declare the dependencies required by a component. Self-type annotation enable us to declare dependencies using traits and the concept of mixins.
In ordinary language, self-type annotations and references make sure that a class will not be detected without mixing traits explicitly, which is specified in the notation. By extending and incorporating a trait, we can use its members in a class more precisely.
Using self-types in traits begins with writing the identifier_name. Next, we write the type of trait to mix in, followed by =>
symbol.
trait vehicle{def doors = 0;}// trait extend another traittrait car extends vehicle{override def doors = super.doors * 2;}// trait extend another traittrait truck extends car{override def doors = 2;}// trait extend another traittrait auto extends vehicle{this: car => override def doors = 2;}object GFG{def main(args:Array[String]){println((new truck with car).doors);println((new auto with car).doors);}}
2
4
Here, in the above example, auto
is an abstract type and self-type of auto
with the car
. ((new auto
with the car
)) conforms to the auto’s
self type with the car
(this: car
=>) A self type allows us to specify what types of traits are allowed to mixin.
Free Resources