Sunday, April 17, 2011

Diamond Problem and Scala Traits

In object-oriented programming languages with multiple inheritance and knowledge organization, the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C?



Java's approach to this problem was to prevent developers to extend from multiple classes but provide them options to implement multiple Interface(s). Scala provides a more clean implementation similar to the Ruby's mixin concept (I'm 0% into Ruby) called Traits. So, how does Scala solve this problem. Check the code below:
TraitLearn.scala

abstract class A{
def isWhat():Boolean
}

trait B extends A{
override def isWhat():Boolean = true;
}

trait C extends A{
override def isWhat():Boolean = false;
}

val a = new A with C with B;
println(a.isWhat());


The output is:

scala TraitLearn.scala
true


So, instead of getting confused to identify which method to execute it has left it to the discretion of the developer. The actual purpose of traits is not what is shown above but what I like it more than the interface is its ability to have partial implementation.

By the way, I bought a new MacBook Pro and the very first thing to try in it was Scala. :-)

No comments: