4 ms·
Java has sum types now with sealed interfaces and pattern matching. Records have detructoring out of the box, and I believe supporting it for general classes is
by za3faran 3y ago
Java has sum types now with sealed interfaces and pattern matching. Records have detructoring out of the box, and I believe supporting it for general classes is in the works.
- cies 3y agoI think sealed interfaces it not quite the same as "tagged unions"-style enum's with payloads. Also, it does not matter much anymore, the whole std-lib is full of exceptions-to-implement-multiple-return-values.
- za3faran 3y agosealed interface Shape {} record Square(int x) implements Shape {} record Rectangle(int l, int w) implements Shape {} record Circle(int r) implements Shape {} double getArea(Shape s) { // Exhaustively checks for all alternatives. return switch (s) { case Square(var x) -> x * x; case Rectangle(var l, var w) -> l * w; case Circle(var r) -> Math.PI * r * r; } } This is a good article: https://mccue.dev/pages/11-1-21-smuggling-checked-exceptions https://mccue.dev/pages/11-1-21-smuggling-checked-exceptions
- cies 3y agoLoved the article. Thanks for sharing. Maybe I (coming from Haskell and Elm) should not be bothered too much with the verbosity of Java/Kotlin "sum types" :)