Sub topic 14
Putting It Together: An Expression Evaluator
This chapter assumes you know Java classes, interfaces, inheritance, switch expressions, instanceof, casting, and basic generics. The examples use record patterns and pattern matching finalized in JDK 21. Unnamed patterns require JDK 22 or newer.
A useful application of pattern matching is an expression evaluator. An expression is a value or operation that produces a value. We can represent each expression as a record and use a sealed interface to list every possible expression type.
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 {}The Expr interface is sealed, so no other class can implement it unless it appears in the permits list. Each record stores the data for one expression shape.
Evaluating the expression tree
An expression tree stores smaller expressions inside larger expressions. For example, 2 * (3 + 4) contains two constants and one addition inside a multiplication.
A switch expression can select a branch by the runtime type of the expression. Record patterns also extract each record component:
static int eval(Expr expression) {
return switch (expression) {
case Const(var value) -> value;
case Add(var left, var right) -> eval(left) + eval(right);
case Mul(var left, var right) -> eval(left) * eval(right);
case Neg(var operand) -> -eval(operand);
};
}The compiler knows that the switch is exhaustive. Expr is sealed, and the switch handles every permitted subtype. No default branch is needed. If a new permitted subtype is added later, this method will normally stop compiling until its case is updated.
The recursive calls evaluate child expressions before applying the operation. For Add, both children are evaluated and then added. For Neg, the child result is given a negative sign.
Simplifying expressions with patterns
Pattern matching can also recognize special structures. The following method performs a few simplifications:
static Expr simplify(Expr expression) {
return switch (expression) {
case Add(Const(var a), Const(var b)) ->
new Const(a + b);
case Mul(Const(var a), var right) when a == 0 ->
new Const(0);
case Mul(Const(var a), var right) when a == 1 ->
right;
default -> expression;
};
}The first case matches an addition whose two children are both constants. The nested record patterns extract their values in one step.
The when clauses act as guards. A guard is an extra boolean condition that must be true after the pattern matches. The specific cases appear before default, so they get a chance to match first.
Here is a complete example:
public class ExpressionDemo {
public static void main(String[] args) {
Expr expression = new Mul(
new Const(2),
new Add(new Const(3), new Const(4)));
System.out.println(eval(expression)); // 14
System.out.println(simplify(
new Add(new Const(3), new Const(4)))); // Const[value=7]
}
static int eval(Expr expression) {
return switch (expression) {
case Const(var value) -> value;
case Add(var left, var right) -> eval(left) + eval(right);
case Mul(var left, var right) -> eval(left) * eval(right);
case Neg(var operand) -> -eval(operand);
};
}
static Expr simplify(Expr expression) {
return switch (expression) {
case Add(Const(var a), Const(var b)) -> new Const(a + b);
case Mul(Const(var a), var right) when a == 0 -> new Const(0);
case Mul(Const(var a), var right) when a == 1 -> right;
default -> expression;
};
}
}
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 {}Exercise
Add a Sub(Expr left, Expr right) record to the hierarchy and update eval so subtraction works.
Show answer
Declare record Sub(Expr left, Expr right) implements Expr {} and add case Sub(var left, var right) -> eval(left) - eval(right); to the switch.