A union type models a domain idea that can be one meaningful alternative or another. Instead of leaving related records floating as unrelated classes, give the alternatives one canonical parent type: a checklist status can be NotStarted, Completed, or Skipped, but never all three at once. This makes the OR in the domain explicit. section 4.3 section 4.9
In Java, a sealed interface represents this kind of sum type. Each permitted implementation is a variant, and the interface says that these options belong to one closed family. Records commonly hold the data of each alternative; sealed interfaces define the choice between them. section 4.6.2 section 4.9
Model a closed choice
A drinks model can state the choice directly: sealed interface Drinks { record Coffee() implements Drinks {} record Tea() implements Drinks {} } Algebraically, Drinks = Coffee + Tea. The plus sign means OR, not that a drink contains both variants. Adding a third permitted variant increases the number of choices the type represents. section 4.6.2
Use a union type when the alternatives carry distinct business meanings:
- Replace a loose collection of related status classes with one named domain category. section 4.3
- Express “these options and no others” rather than relying on runtime if/else conditions to distinguish states. section 4.9 section 5.9
- Model optionality as a choice between a value-bearing case and an empty case. section 4.6.4
- Build recursive data such as business rules, where equality, AND, OR, and NOT are all variants of Rule. section 8.4
Sum types compose with product types. A record combines fields with AND semantics, while a sealed interface combines variants with OR semantics. Keeping that distinction visible helps prevent a record from accumulating fields whose meanings conflict, and gives a compact notation for sketching and refactoring a domain model. section 4.6.2 section 4.6.3 section 4.6.4
Listing 8.13 An algebra appears!
sealed interface Rule {
record Equals(Attribute field, String value) implements Rule {}
record And(Rule a, Rule b) implements Rule {}
record Or(Rule a, Rule b) implements Rule {}
}The Rule hierarchy shows a union type used recursively: every rule is exactly one variant, while And, Or, and Not contain other Rule values. section 8.4
On older Java versions, the domain design still matters even without sealed interfaces. Group related implementations in one file or mark the intent with documentation or an annotation convention, while recognizing that these conventions do not make Java enforce the closed set. section 4.7












