top | item 37159292

(no title)

danieldisu | 2 years ago

It is way easier for me to read than what you proposed in Typescript, more characters to write? sure but how many times do I have to write a piece of code and how many times do I have to read it?

I guess ultimately it depends on which language you are more familiar with...

discuss

order

ollysb|2 years ago

I'm more than happy with either of those variations. My favourite though would be Elm's syntax ;)

    type Message 
        = IncrementBy Int
        | DecrementBy Int
        | Set Int

munificent|2 years ago

One big difference between how Dart (and other OO languages that take a similar approach) and what Elm and other functional languages do is that in Dart, each of the cases is also its own fully usable type.

In Dart, if you do:

    sealed class Message {}

    class IncrementBy extends Message {
      final int amount;
      IncrementBy(this.amount);
    }

    class DecrementBy extends Message {
      final int amount;
      DecrementBy(this.amount);
    }

    class Set extends Message {
      final int amount;
      Set(this.amount);
    }
You can then write functions that accept specific cases, like:

    onlyOnIncrement(IncrementBy increment) {
      ...
    }
In Elm and friends, IncrementBy is just a type constructor, not a type. Further, we can use the class hierarchy to reuse shared state and behavior in a way that sum types don't let you easily do. In your example, each case has an int and it so happens that they reasonably represent roughly the same thing, so you could do:

    sealed class Message {
      final int amount;
      Message(this.amount);    
    }

    class IncrementBy extends Message {
      IncrementBy(super.amount);
    }

    class DecrementBy extends Message {
      DecrementBy(super.amount);
    }

    class Set extends Message {
      Set(super.amount);
    }
And now you can write code that works with the amount of any Message without having to pattern match on all of the cases to extract it:

    showAmount(Message message) {
      print(message.amount);
    }
So, yes, it's more verbose than a sum type (and we do have ideas to trim it down some), but you also get a lot more flexibility in return.