What is self-type in Scala?

Self-type annotations/references allow us to redefine the thispointer 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.

Code

trait vehicle
{
def doors = 0;
}
// trait extend another trait
trait car extends vehicle
{
override def doors = super.doors * 2;
}
// trait extend another trait
trait truck extends car
{
override def doors = 2;
}
// trait extend another trait
trait 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);
}
}

Output

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

Copyright ©2025 Educative, Inc. All rights reserved