1.

What Is Diamond Problem? How Scala Solves Diamond Problem?

Answer»

A Diamond Problem is a Multiple Inheritance problem. Some people calls this problem as Deadly Diamond Problem.

In Scala, it OCCURS when a Class extends more than one Traits which have same method definition.

Unlike Java 8, Scala solves this diamond problem automatically by following some rules defined in Language. Those rules are called “Class LINEARIZATION”.

Example:-

trait A{
def display(){ println("From A.display") }
}
trait B extends A{ 
override def display() { println("From B.display") }
}
trait C extends A{ 
override def display() { println("From C.display") }
}
class D extends B with C{ }
 
object ScalaDiamonProblemTest extends App {
VAL d = new D
d display
}

Here OUTPUT is “From C.display” form trait C. Scala Compiler reads “extends B with C” from right to left and takes “display” method definition from lest most trait that is C.

A Diamond Problem is a Multiple Inheritance problem. Some people calls this problem as Deadly Diamond Problem.

In Scala, it occurs when a Class extends more than one Traits which have same method definition.

Unlike Java 8, Scala solves this diamond problem automatically by following some rules defined in Language. Those rules are called “Class Linearization”.

Example:-

trait A{
def display(){ println("From A.display") }
}
trait B extends A{ 
override def display() { println("From B.display") }
}
trait C extends A{ 
override def display() { println("From C.display") }
}
class D extends B with C{ }
 
object ScalaDiamonProblemTest extends App {
val d = new D
d display
}

Here output is “From C.display” form trait C. Scala Compiler reads “extends B with C” from right to left and takes “display” method definition from lest most trait that is C.



Discussion

No Comment Found