3 ms·
Sum types are amazing! Once I got introduced to them in Rust, it was hard to go back to languages like Java where the enum type is pitiful in comparison.
by BD103 3y ago
Sum types are amazing! Once I got introduced to them in Rust, it was hard to go back to languages like Java where the enum type is pitiful in comparison.
- kaba0 3y agoJava literally has algebraic data types, see sealed classes/interfaces and records.
- diarrhea 3y agoNot familiar with Java, but C# has sealed classes as well. They are not the real deal. You can fake your way around to achieve something resembling sum types, but the deep language integration like in Rust is simply unattainable. For example, ADT and pattern matching go hand in hand, so you want syntax-level, first class and powerful support for structural pattern matching as well. Not sure about Java, but last I used it C# had only relatively basic support.
- kaashif 3y agoJava actually does have pattern matching like this: int eval(Expr e) { return switch (e) { case ConstantExpr(var i) -> i; case PlusExpr(var a, var b) -> eval(a) + eval(b); case TimesExpr(var a, var b) -> eval(a) \* eval(b); case NegExpr(var e) -> -eval(e); // no default needed, Expr is sealed } } But it only got that recently.
- kaba0 3y agoAnd further improvements are expected.
- diarrhea 3y agoWishing that eco system the best then! ADTs and pattern matching are the best thing since sliced bread. Sometimes I wonder: will they become table stakes in the future, or will we wake up to their (currently unknown) downsides in a decade or two? Think of how exceptions are now considered a poor pattern, compared to errors as values.