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:
Post a Comment