Scala allow the multiple trait mix-in.
On the Java, java also allow the multiple interface implementation. What is the difference between Scala's trait and Java's interface? There are similar thing. We use trait as interface define. But, trait can have it own field and implementation of there defined method. Java's interface cannot it own some values and implementations that the interface defined the methods.
I had a question about trait mix-in. The question is "when some of traits are defined same name of methods and the methods also have some different implements then which method will be active?"
For example,
---------------------------------------------------------
trait A { def x = println("A......x")}
trait B { def x = println("B......x")}
class C extends A with B
class D extends B with A
---------------------------------------------------------
In such case, trait A and B define the method named x. And both x on each trait have also implementation. When we want to define the class C and D what will be happened? You can see only error when you will compile it. The error meaning is we need override the method x in class C and D... On my 1st idea, scala compiler will chose one of implements by the priority. The really behavior of compiler, this idea was false. We have define the new method with "override".
So, we need to write code as following thing. When we define the class C and D, we need also to define the method x on each class with "override" keyword.
------------------------------------------------------------
trait A { def x = println("A......x")}
trait B { def x = println("B......x")}
class C extends A with B { override def x = println("C.........x")}
class D extends B with A { override def x = println("B.........x")}
------------------------------------------------------------
Comments