Home » Scala language

Trait Linearization in Scala

Scala | Trait Linearization: Trait linearization is an important feature in Scala which eliminates ambiguity when traits and classes are inherited by a class.
Submitted by Shivang Yadav, on March 08, 2020

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).


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.


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

This sample program will make the concept more clear,

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 833 -> "+ super.method 

object myObject 
	def main(args: Array[String]) 
		var myBike = new iron 


Iron 833 -> Harley Davidson-> Muscle Bike -> Bike-> vehicle 

Features of trait linearization

  • 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.

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.