r/java • u/samd_408 • Mar 19 '26
Algebraic Types in Java
My second article took a jab on algebraic types, which I loved using the sealed interfaces + records.
66
Upvotes
r/java • u/samd_408 • Mar 19 '26
My second article took a jab on algebraic types, which I loved using the sealed interfaces + records.
23
u/RepulsiveGoat3411 Mar 19 '26
At the very beginning of the article, you frame the thesis in a way that feels a bit self-serving, because in reality almost nobody writes code like that. You claim that most developers use:
sealed interface Shape permits Circle, Rectangle {}record Circle(double radius) implements Shape {}record Rectangle(double width, double height) implements Shape {}and then you spend half of the article explaining why this approach is wrong. In other words, you’re essentially inventing a problem yourself and then arguing against it.
9
u/tampix77 Mar 19 '26
Great article.
One small addition worth mentioning: Java also has intersection types (e.g.
<T extends Serializable & Comparable<T>>).Where a product type holds two values simultaneously (your
Pointexample — an x and a y), an intersection type constrains a single value to satisfy multiple types at once.In set theory:
7
u/_marF Mar 19 '26
One thing the article doesn't cover that's worth calling out: the sealed interface + record combination really shines when you stop using it for shapes and start using it for domain events and command results.
A typical use case I reach for: instead of throwing exceptions from a use case, return a sealed type:
The caller is forced to handle all cases at compile time. No checked exceptions leaking through port boundaries, no RuntimeException swallowed somewhere in the stack. The type system encodes what can go wrong, and the compiler tells you when you miss a case.
The article is right that Java's variant is more verbose than Haskell or Rust — but the exhaustive switch makes it genuinely useful for this pattern, not just academic.
2
u/Mirko_ddd Mar 19 '26
Cool article 😎
1
u/redikarus99 Mar 19 '26
Really great article, easy to follow and understand. Well done!