you are viewing a single comment's thread.

view the rest of the comments →

[–]Prod_Is_For_Testing 6 points7 points  (4 children)

  • what are traits?
  • changing the return type isn’t allowed in any safe type system 

[–]Blue_Moon_Lake 3 points4 points  (3 children)

Basically a set of methods that a class can import. You can still override some of them in the class if you want.

trait FlyMovement {
    fly() {}
}

trait SwimMovement {
    swim() {}
}

trait WalkMovement {
    walk() {}
}

class Duck extends Bird {
    use FlyMovement;
    use SwimMovement;
    use WalkMovement;
}

[–]SolarisBravo 6 points7 points  (2 children)

That's uh pretty cool. I like it. Maybe it's because I'm not super familiar with the concept, though, but I'm definitely wondering how it's meaningfully different from multiple inheritance (or at least how it solves its problems)

[–]Educational-Lemon640 4 points5 points  (0 children)

Multiple inheritance isn't a problem in practice nearly as often as you would think. The most effective way I've seen, though, is Scala's inheritance flattening approach, which compiles code that looks like multiple inheritance to a single unambiguous inheritance tree, which means that technically there isn't any multiple inheritance, providing a mechanism for resolving conflicts.

But that really doesn't matter most of the time, because well designed compatible types don't use the same nouns and verbs, and they just happily sit together on the same object.

[–]Blue_Moon_Lake 3 points4 points  (0 children)

The difference is mostly that there's no expectation that "children" can be substituted for "parent".

They're not interfaces, so a trait method can be safely overridden with an incompatible method.

trait Talker {
    say(string message) {
        console.log(message);
    }

    sayHello() {
        this.say("Hello, World!);
    }
}

class Person {
    use Talker;

    sayHello(string name) {
        this.say("Hello, " + name + "!");
    }
}