Diamond Issue with Groovy traits

2019-07-04 06:46发布

问题:

In many blog about Groovy Traits it's mentioned that it will solve the Diamond Problem. But the concept is not clear to me that how traits will solve the Diamond Problem.

Can any one explain please.

回答1:

The diamond problem is a problem when you have multiple inheritance and two or more super classes define one or more functions with the same signature.

With groovy traits, the behaviour is well-defined. By default, the last implementation is chosen.

trait A {
    String name() { "A" }
}
trait B {
    String name() { "B" }
}
class C implements A,B { }
class D implements B,A { }

assert new C().name() == "B"
assert new D().name() == "A"

It is also possible to choose the one you want:

class E implements A,B {
    String name() { A.super.name() + B.super.name() }
}

assert new E().name() == "AB"


标签: groovy traits