Sub topic 14
Putting it together: an expression evaluator
This chapter combines the earlier pieces into one small program: a sealed interface, records, nested record patterns, guards, and exhaustive switches. It assumes you have read the earlier chapters on type patterns, when guards, dominance, sealed interfaces and record patterns. It needs JDK 22 or newer because of the unnamed pattern _. On JDK 21, replace each _ with var ignored.
The design: data on one side, operations on the other
Data-oriented design separates what the data is from what you do with it. Here the data is a small arithmetic language:
Expris a sealed interface that lists every kind of expression.- Four records carry the data:
Const,Add,MulandNeg. - Ordinary static methods hold the operations (
eval,show,simplify). Each one is a switch overExpr.
The records have no behavior. Adding an operation means writing one new method and touching no existing class. The cost is on the other axis: adding a new kind of expression means revisiting every switch. Sealing the interface makes the compiler find those switches for you.
Each pattern you write follows this shape. Add(Const(var a), Const(var b)) describes the Add node whose two children are both constants.
The types
sealed interface Expr permits Const, Add, Mul, Neg {}
record Const(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Mul(Expr left, Expr right) implements Expr {}
record Neg(Expr operand) implements Expr {}Records are transparent: the compiler knows their components and their order. That lets a record pattern take an instance apart without any accessor calls in your code. The permits clause gives the compiler the full list of subtypes, which it needs to check exhaustiveness.
Evaluating: one case per record
static int eval(Expr e) {
return switch (e) {
case Const(var v) -> v;
case Add(var l, var r) -> eval(l) + eval(r);
case Mul(var l, var r) -> eval(l) * eval(r);
case Neg(var o) -> -eval(o);
};
}There is no default. The four record patterns cover every permitted subtype of Expr, so the compiler accepts the switch as exhaustive. Each var takes the type of its record component. In Add(var l, var r), both l and r are Expr, so the recursive calls type-check with no casts.
Two behaviors are worth knowing. The switch has no case null, so eval(null) throws NullPointerException. Arithmetic uses plain int, so large values overflow silently.
Printing: another operation, same shape
static String show(Expr e) {
return switch (e) {
case Const(var v) -> Integer.toString(v);
case Add(var l, var r) -> "(" + show(l) + " + " + show(r) + ")";
case Mul(var l, var r) -> show(l) + " * " + show(r);
case Neg(var o) -> "-(" + show(o) + ")";
};
}Add adds its own parentheses, so a sum inside a product prints correctly without precedence logic. This is a shortcut for the demo. A production printer would track operator precedence.
Simplifying: nested patterns and guards
Simplification rewrites a node when its shape matches a known identity. Here nested record patterns do the most work, because a rule often depends on the children.
static Expr simplify(Expr e) {
return switch (e) {
case Add(Const(var a), Const(var b)) -> new Const(a + b);
case Add(Const(var a), var r) when a == 0 -> r;
case Add(var l, Const(var b)) when b == 0 -> l;
case Mul(Const(var a), Const(var b)) -> new Const(a * b);
case Mul(Const(var a), _) when a == 0 -> new Const(0);
case Mul(_, Const(var b)) when b == 0 -> new Const(0);
case Mul(Const(var a), var r) when a == 1 -> r;
case Mul(var l, Const(var b)) when b == 1 -> l;
case Neg(Const(var v)) -> new Const(-v);
case Neg(Neg(var inner)) -> inner;
case Const c -> c;
case Add add -> add;
case Mul mul -> mul;
case Neg neg -> neg;
};
}Four details in this method matter.
- Order is part of the meaning. Cases are tried from top to bottom.
Mul(Const, Const)comes before the guarded rules so that two constants fold to a single constant. - Guards do not cause dominance errors. A guarded case never dominates a later case, because the compiler cannot prove the guard is always true. The unguarded
case Add addafter the guardedAddcases is legal. The reverse order would not compile, becauseAdd addwould dominate everything after it. - The unnamed pattern
_marks a component you do not read. InMul(Const(var a), _)the right child is irrelevant, because the result is0whatever it is. - The last four cases replace
default. They return unchanged any node that no rule matched. If you wrotedefault -> einstead, the switch would still compile, but it would also hide a missing case when you add a new subtype. Naming the remaining cases keeps the exhaustiveness check active.
simplify rewrites only the node it receives. To simplify a whole tree, rebuild the children first and then apply the rules to the parent:
static Expr simplifyAll(Expr e) {
Expr rebuilt = switch (e) {
case Const c -> c;
case Add(var l, var r) -> new Add(simplifyAll(l), simplifyAll(r));
case Mul(var l, var r) -> new Mul(simplifyAll(l), simplifyAll(r));
case Neg(var o) -> new Neg(simplifyAll(o));
};
return simplify(rebuilt);
}Working from the leaves up means each rule sees children that are already simplified. A Neg(Neg(Const 0)) folds to Const(0) before its parent Add looks at it.
The complete program
Save this as ExprDemo.java and run it with java ExprDemo.java.
public class ExprDemo {
sealed interface Expr permits Const, Add, Mul, Neg {}
record Const(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Mul(Expr left, Expr right) implements Expr {}
record Neg(Expr operand) implements Expr {}
static int eval(Expr e) {
return switch (e) {
case Const(var v) -> v;
case Add(var l, var r) -> eval(l) + eval(r);
case Mul(var l, var r) -> eval(l) * eval(r);
case Neg(var o) -> -eval(o);
};
}
static String show(Expr e) {
return switch (e) {
case Const(var v) -> Integer.toString(v);
case Add(var l, var r) -> "(" + show(l) + " + " + show(r) + ")";
case Mul(var l, var r) -> show(l) + " * " + show(r);
case Neg(var o) -> "-(" + show(o) + ")";
};
}
static Expr simplify(Expr e) {
return switch (e) {
case Add(Const(var a), Const(var b)) -> new Const(a + b);
case Add(Const(var a), var r) when a == 0 -> r;
case Add(var l, Const(var b)) when b == 0 -> l;
case Mul(Const(var a), Const(var b)) -> new Const(a * b);
case Mul(Const(var a), _) when a == 0 -> new Const(0);
case Mul(_, Const(var b)) when b == 0 -> new Const(0);
case Mul(Const(var a), var r) when a == 1 -> r;
case Mul(var l, Const(var b)) when b == 1 -> l;
case Neg(Const(var v)) -> new Const(-v);
case Neg(Neg(var inner)) -> inner;
case Const c -> c;
case Add add -> add;
case Mul mul -> mul;
case Neg neg -> neg;
};
}
static Expr simplifyAll(Expr e) {
Expr rebuilt = switch (e) {
case Const c -> c;
case Add(var l, var r) -> new Add(simplifyAll(l), simplifyAll(r));
case Mul(var l, var r) -> new Mul(simplifyAll(l), simplifyAll(r));
case Neg(var o) -> new Neg(simplifyAll(o));
};
return simplify(rebuilt);
}
public static void main(String[] args) {
Expr e = new Add(
new Mul(new Const(1), new Add(new Const(2), new Const(3))),
new Neg(new Neg(new Const(0))));
System.out.println(show(e));
System.out.println(eval(e));
System.out.println(show(simplify(e)));
System.out.println(show(simplifyAll(e)));
System.out.println(show(simplify(new Mul(new Const(1), new Add(new Const(2), new Const(3))))));
}
}The output is:
(1 * (2 + 3) + -(-(0)))
5
(1 * (2 + 3) + -(-(0)))
5
(2 + 3)The third line shows that simplify alone changes nothing on the root. The root is an Add whose children are not constants, so no rule fires. The fifth line shows the Mul(Const(1), r) rule returning the right child.
Failure modes and design trade-offs
A sealed hierarchy with no default makes the compiler report every switch that must change when the hierarchy changes. If you add record Sub(Expr left, Expr right) implements Expr {} to the permits list, eval, show and simplifyAll stop compiling until you handle Sub.
The check happens at compile time. If a class is compiled separately and the hierarchy later gains a subtype, an already-compiled exhaustive switch can meet a value it has no case for. In that situation it throws MatchException. A record accessor that throws during deconstruction also surfaces as a MatchException. Both cases are rare, and both are a reason to recompile everything when you change a sealed hierarchy.
| Choice | Benefit | Cost |
|---|---|---|
| Sealed interface plus switches | New operations are one method. The compiler checks coverage. | New subtypes touch every switch. |
| Methods on each record | New subtypes are local. | Each new operation touches every record. |
| `default` branch | Short code. | The compiler stops reporting missing cases. |
| Explicit remaining cases | Exhaustiveness stays checked. | More lines. |
Exercise
You add record Sub(Expr left, Expr right) implements Expr {} and put Sub in the permits clause of Expr. Which of the methods eval, show and simplify in the complete program stop compiling, and why?
Show answer
eval and show stop compiling, because their switch expressions have no default and no case for Sub, so they are no longer exhaustive. simplify still compiles. Its last four cases are Const, Add, Mul and Neg only, so it is also no longer exhaustive and fails to compile. Only a default branch would have kept it compiling, and that branch would have hidden the missing Sub case.
Exercise
What does show(simplifyAll(new Mul(new Const(0), new Neg(new Add(new Const(1), new Const(2)))))) print?
Show answer
It prints 0. simplifyAll first reduces the right child: Add(1, 2) becomes Const(3), then Neg(Const(3)) becomes Const(-3). The parent is then Mul(Const(0), Const(-3)), and the first Mul rule (two constants) folds it to Const(0).