This macro allows to reuse code in different classes, which can't extend each other.
- Static vars / methods inheritance (even inlined)
- Multiple inheritance
- "Lazy" interfaces: traits methods are copied to descendant class, so you don't need to write implementation in each class, which implements trait. But you still can skip implementation of some methods in trait to force each descendant implement these methods (It's a sort of "classic" abstracts from Java or PHP)
- Ability to "override" trait's methods
- Access descendant class in trait's code via
traits.Trait.self()
- In overriden methods call "super" methods via
traits.Trat.parent(TTraitClass).someMethod()
(likesuper.someMethod()
for normal inheritance) - In trait's code you can access fields, which are not declared in trait, but will be declared in descendant class example
haxelib install traits
interface TWorker extends traits.ITrait{
public function work() : Void {
trace("I'm working!");
}
}
interface TReader extends traits.ITrait{
public function read() : Void {
trace("I'm reading!");
}
}
class Test implements TWorker implements TReader {
public function new() : Void {
this.work(); //output: "I'm working!"
this.read(); //output: "I'm reading!"
}
}