Resolve diamond inheritance when a class adopts two traits that share a parent.
← Sealed Types and Traits · Ref: Q1131
Resolve diamond conflicts with explicit override:
DiamondClass with trait of LeftTrait, RightTrait override getShared() as pure <- rtn as String: "diamond-shared"
When two traits extend the same parent, conflicting methods must be overridden. Use TraitName.methodName() to call a specific trait's version.
See Q1129 for basic delegation. See Q1132 for explicit trait calls.
Example
defines module qa.sealedtraits.traitdiamond defines trait TopTrait getShared() as pure <- mainValue as String: "top-shared" LeftTrait is TopTrait override getShared() as pure <- mainValue as String: "left-shared" RightTrait is TopTrait override getShared() as pure <- mainValue as String: "right-shared" defines class DiamondClass with trait of LeftTrait, RightTrait //Must override to resolve the conflict override getShared() as pure <- mainValue as String: "diamond-resolved" //Explicit access to each trait's version getLeftVersion() as pure <- mainValue as String: LeftTrait.getShared() getRightVersion() as pure <- mainValue as String: RightTrait.getShared() default operator ? defines program TraitDiamondDemo() stdout <- Stdout() diamond <- DiamondClass() stdout.println(`Resolved: ${diamond.getShared()}`) stdout.println(`Left: ${diamond.getLeftVersion()}`) stdout.println(`Right: ${diamond.getRightVersion()}`)
Common mistakes
E05120 — Conflicting trait methods require the 'override' keyword to resolve the ambiguity.
Incorrect:
getShared() as pure <- rtn as String: "resolved"
Correct:
override getShared() as pure <- mainValue as String: "left-shared"
Other ways to ask this
- I have LeftTrait and RightTrait both extending TopTrait — resolve the conflict
- In Java interfaces with diamond inheritance need default method resolution. Show the EK9 way
- Given a diamond pattern with conflicting methods, override to resolve them
- Handle the case where two traits provide conflicting implementations of the same method
Coming from another language?
Java: interface default method conflict requires explicit override. C#: explicit interface implementation. EK9: override conflicting methods + TraitName.method() for explicit access.
Keywords: trait, multiple, resolve, diamond, override, conflict