Home »
Scala
Trait Linearization in Scala
By IncludeHelp Last updated : October 26, 2024
Scala Trait Linearization
In Scala programming language, trait linearization is a property that helps to rectify ambiguity when instances of a class that are defined using multiple inheritances from different classes and traits are created.
It resolves ambiguity that may arise when class or trait inherits property from 2 different parents (they may be classes or traits).
Syntax
trait t1{}
class c1{}
class main{}
object obj1 = new class main extents c1 with t1
Here linearization will make the inheritance structure clear so that no problem could arise in the future.
Here, we will consider two root classes, AnyRef root for all reference types. Any root for all classes in Scala.
Linearization
t1 -> AnyRef -> Any
c1 -> AnyRef -> Any
main -> AnyRef -> Any
obj1 -> main -> t1 -> c1 -> AnyRef -> Any
Here the linearization will go in the following order: main class -> t1 trait -> c1 class -> AnyRef -> Any
Example of Trait Linearization
class Vehicle {
def method: String = "Vehicle"
}
trait Bike extends Vehicle {
override def method: String = "Bike -> " + super.method
}
trait MuscleBike extends Vehicle {
override def method: String = "Muscle Bike -> " + super.method
}
trait Harley extends Vehicle {
override def method: String = "Harley Davidson -> " + super.method
}
class Iron extends Bike with MuscleBike with Harley {
override def method: String = "Iron 883 -> " + super.method
}
object MyObject {
def main(args: Array[String]): Unit = {
val myBike = new Iron
println(myBike.method)
}
}
Output
Iron 833 -> Harley Davidson-> Muscle Bike -> Bike-> vehicle
Features of Trait Linearization
Key aspects of trait linearization in Scala include the following:
- It is used to solve ambiguity in Scala which arises in the case of multiple inheritances.
- The calling of a super method by subclasses is managed using stack.
- Linearization comes into play when a new class instance is created.
- Linearization may not be the same as inherited mixins because mixins are defined by the programmer.
- Linearization avoids repeated inheritance and if we explicitly try to add a class to inheritance an error will be thrown.