2 ms·
Sum types and subclasses cover much of the same problem space just with different trade-offs. Sum types give you exhaustiveness checking, while subclasses give
by munificent 12y ago
Sum types and subclasses cover much of the same problem space just with different trade-offs. Sum types give you exhaustiveness checking, while subclasses give you open-ended extensibility.
Given that Dart already has subclasses and they're the natural way for people to solve most problems where you'd reach for a sum type in other languages, I don't think there's as much need for enums to be larger and feature-rich. Instead, the language team focused them on the narrow use cases of wanting just an exhaustively checked numeric subrange, similar to enums in C#.
I do personally wish you could add methods and fields to them (á la Java but without case-specific methods and fields), but I think the language team wanted something easier to compile to a bare number in JS. Maybe they'll get added later.
- pacala 12y agoUnless I'm missing something, enums are closed, thus overlap with sum types for the use-cases. Subclasses are an implementation detail in this context. Here is an example that uses subclasses to implement generalized enums, aka sum types: enum List { Cons(head, tail) {...} Nil {...} int length() { switch (this) { case Cons(head, tail): return 1 + length(tail) case Nil: return 0 } } } Mind you, this is syntactic sugar and you can do it by hand with enums + sublcasses. But the whole point of clean languages is to remove unnecessary boilerplate :)
- jdonaldson 12y agoHaxe has another example of this: http://haxe.org/manual/types-enum-instance.html http://haxe.org/manual/types-enum-instance.html Note that enums in Haxe are pure data types, and can't have member functions and/or values. However, since enums are public by nature, it's possible to achieve this easily with "using": http://try.haxe.org/#87bF5 http://try.haxe.org/#87bF5