Diamond Issue with Groovy traits

邮差的信 提交于 2019-12-23 19:37:54

问题


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"


来源:https://stackoverflow.com/questions/46905780/diamond-issue-with-groovy-traits

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!