• anlumo@feddit.de
    link
    fedilink
    arrow-up
    5
    ·
    9 months ago

    I recently caught myself trying to do traits in an OOP language. Failed spectacularly of course.

    But it would be so much easier to read…

    • Tempy@lemmy.temporus.me
      link
      fedilink
      arrow-up
      1
      ·
      9 months ago

      Depending on your language, your closest analogue is going to be interfaces. C# even has a where clause where you can restrict a generic type such that any type substituted must implements one or more interfaces. You can get quite a bit of trait like working there, from the function input side of stuff.

      The biggest problem is, you can’t implement an interface for a type unless you have access to the type. So you’d have to really on wrapping types you don’t own to apply trait like interfaces to it.

      And then there’s minor issues like, no such thing as associated types, or being able to specify constants in a definition. But you can usually work around that in a less nice way.

      • anlumo@feddit.de
        link
        fedilink
        English
        arrow-up
        1
        ·
        9 months ago

        In my case, it was in Dart. Dart allows extending existing classes with new methods, but unfortunately this doesn’t allow implementing abstract mixins (which is the equivalent of Rust’s trait) on other types. Dart is in this weird middle where it’s not really strictly typed (it has dynamic, which is like the any type in TypeScript), but the compiler doesn’t allow ducktyping anyways.