Sub topic 8
Modeling Data Variants with Sealed Interfaces and Records
Assume you know Java interfaces, inheritance, records, switch expressions, and basic generics. This chapter uses pattern matching for switch, which requires Java 21 or later.
Many programs represent one value that can have several forms. A payment might be a card payment, a bank transfer, or a cash payment. An expression might be a number, an addition, or a multiplication.
A sealed interface models this closed set of variants. Each variant is a permitted implementation. Records work well for the variants because they concisely store their data and provide accessors.
Sum types and product types
A sealed hierarchy is similar to a sum type: a value is one of several alternatives. Each record is similar to a product type: it combines several fields into one value.
For an arithmetic expression, the alternatives are:
Num, which contains one integer.Add, which contains a left and right expression.Mul, which also contains a left and right expression.
The child expressions can themselves contain more expressions. This gives us a tree.
public class Main {
sealed interface Expr {
record Num(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Mul(Expr left, Expr right) implements Expr {}
}
static int eval(Expr expression) {
return switch (expression) {
case Expr.Num n -> n.value();
case Expr.Add(Expr left, Expr right) ->
eval(left) + eval(right);
case Expr.Mul(Expr left, Expr right) ->
eval(left) * eval(right);
};
}
public static void main(String[] args) {
Expr expression = new Expr.Mul(
new Expr.Add(new Expr.Num(2), new Expr.Num(3)),
new Expr.Num(4)
);
System.out.println(eval(expression));
}
}The program prints:
20The expression represents (2 + 3) * 4.
Record deconstruction in a switch
The case Expr.Add(Expr left, Expr right) pattern does two jobs:
- It checks that the value is an
Add. - It extracts the record components into
leftandright.
Without a record pattern, the same case would require an explicit accessor call:
case Expr.Add add -> eval(add.left()) + eval(add.right());The record pattern is useful when the components are immediately needed. It also makes recursive data processing easier to read.
Why no default case is needed
The compiler knows that Expr has exactly three permitted variants: Num, Add, and Mul. The switch handles all three, so it is exhaustive.
This is valuable when the variants represent business cases. If someone adds a new permitted subtype, existing exhaustive switches can fail to compile until they handle the new case. The compiler therefore helps locate code that needs updating.
A default branch would hide that benefit. Use one only when you deliberately want unknown future variants to share fallback behavior.
Choosing this model
Sealed interfaces and records fit data that has a small, known set of forms, especially when each form has different fields. They are often clearer than one class with many nullable fields.
An enum is simpler when every variant is just a name and carries no different data. An open interface is better when external code should add implementations, such as a plugin system. An abstract class can be preferable when variants share substantial mutable state or implementation.
Exercise
Add a Negate(Expr expression) record and update eval so that -x returns the negative value of x.
Show answer
Declare record Negate(Expr expression) implements Expr {} inside Expr, add case Expr.Negate(Expr value) -> -eval(value);, and include Negate in the permitted variants if your compiler requires an explicit permits clause.