3 ms·
Sum types are coming to Java in the form of sealed classes: https://openjdk.java.net/jeps/397 https://openjdk.java.net/jeps/397
by oftenwrong 6y ago
Sum types are coming to Java in the form of sealed classes:
https://openjdk.java.net/jeps/397 https://openjdk.java.net/jeps/397
- Twisol 6y agoTo be fair, Java has always supported a particular flavor of sum types founded on subtyping: use an abstract class with a private constructor as a base, add nested static final subclasses for the variants, and decide whether to use instanceof or the Visitor pattern to dispatch on each variant. (The Visitor approach corresponds to a certain isomorphism -- the sum type `A + B` is equivalent to `forall T. (A -> T, B -> T) -> T`, where the pair of handlers `(A -> T, B -> T)` is the titular visitor.) That JEP elaborates on the same ideas (notably using `instanceof` instead), as the linked JEP explains, but the motivation for sealed classes extends to further harmony with subtyping. The major item seems, to me, to be allowing interfaces to be a supertype. A minor but distinctive item is that the sum type's variants can be defined at (some) distance from the base type, rather than all being defined in a single breath. The problem is, even though you could always express sum types in Java, it's verbose, unpleasant, and above all "clever" in a way unnecessary in other languages. I think this JEP helps somewhat -- the private constructor trick in particular goes away -- but it doesn't really help with clients of your sum type. Pattern matching is still yet to come, and if you want a Visitor, you still need to write a Visitor. To the grandparent's point, this JEP isn't enough to provide a coherent alternative to checked exceptions or other kinds of structured control flow.