Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala

What is self-type in Scala?

Behzad Ahmad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

scala

CONTRIBUTOR

Behzad Ahmad
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring