1.

What is the linearization rule in Scala?

Answer»

When a class extends multiple traits, it might happen that they have a common method. Now when that method is executed, it is very important to know the trait on which the method is INVOKED first. The linearization rule says that the common method execution WOULD start in the traits from right to left as it is mentioned in the extends list.

Even if the traits have a common super trait or abstract class, the execution order would be linear so that no conflicts arise. Let’s take an example:

abstract class A { def stringValue = "A " } trait AT extends A { override def stringValue = "AT " + super.stringValue } trait BT extends A { override def stringValue = "BT " + super.stringValue } trait CT extends BT with AT { override def stringValue = "CT " + super.stringValue } class D extends CT { override def stringValue = "D " + super.stringValue } /* The class hierarchy: A \ \ / CT | D */ println(new D().stringValue)

Though the class hierarchy is like a graph, the execution of the method stringValue FOLLOWS a particular order based on the linearization rule:

D CT AT BT A

This implies that if a class or trait extends multiple traits, such a common method execution starts from the extreme right in the extends list. That’s why stringValue of AT executed before that of BT.



Discussion

No Comment Found