Quick revision
The short answer
The evaluator is one switch expression with a record pattern per type: int eval(Expr e) { return switch (e) { case Num(int v) -> v; case Add(Expr l, Expr r) -> eval(l) + eval(r); case Mul(Expr l, Expr r) -> eval(l) * eval(r); }; }. No default is needed because Expr is sealed and every permitted subtype is covered, and the record patterns pull out the components directly instead of calling accessors. A guarded case such as case Mul(Num(int z), Expr r) when z == 0 -> 0 can short-circuit multiplication by zero, as long as it comes before the general Mul case.
What to remember
In this answer, we wrote the evaluator as a single switch expression with one record pattern per node type, recursing into the children of Add and Mul. Because Expr is sealed, the switch needs no default and the compiler checks that every type is covered. Record patterns removed the accessor calls, nested patterns and a when guard let us short-circuit multiplication by zero, and we saw that the guarded case must come before the general Mul case, or the compiler rejects it as dominated.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The evaluator is one switch expression with a record pattern per type: int eval(Expr e) { return switch (e) { case Num(int v) -> v; case Add(Expr l, Expr r) -> eval(l) + eval(r); case Mul(Expr l, Expr r) -> eval(l) * eval(r); }; }. No default is needed because Expr is sealed and every permitted subtype is covered, and the record patterns pull out the components directly instead of calling accessors. A guarded case such as case Mul(Num(int z), Expr r) when z == 0 -> 0 can short-circuit multiplication by zero, as long as it comes before the general Mul case.
Why this question is asked
An expression evaluator is the classic example for pattern matching, because a tree of expressions is exactly the kind of data that sealed types and records describe well. Interviewers use it to see whether we can combine Java 21 features fluently and whether we understand exhaustiveness and case ordering. In this answer, we will recap the data model, write the evaluator step by step, test it on a small tree, add the zero guard and see why its position matters, and finally extend the model with a new operation.
1A Quick Recap of the Data Model
The interface Expr is sealed, which means it lists the only types allowed to implement it: Num, Add and Mul. Each is a record, a class that just holds data and is implicitly final. Num holds a number, while Add and Mul hold two child expressions, so together they form a tree. The expression 2 + 3 * 4 is an Add whose left side is Num(2) and whose right side is a Mul of Num(3) and Num(4).
A record pattern, final in Java 21, matches a record by type and binds its components to variables at the same time. case Add(Expr l, Expr r) means: if the value is an Add, name its left part l and its right part r.
- Add(l, r)Root: evaluates l + r
- Num(2) and Mul(l, r)Left is a leaf; right multiplies
- Num(3) and Num(4)Leaves under Mul
3 layers, from the top down. Step through them one at a time.
eval walks down the tree and adds or multiplies on the way back up.
2Writing the Evaluator
Each case matches one kind of node. A Num returns its value. An Add or Mul evaluates both children recursively and combines the results.
Notice three things. There is no default branch: the compiler knows from the sealed declaration that an Expr can only be Num, Add or Mul, and all three are covered, so the switch is exhaustive. There are no accessor calls such as add.l() or casts; the pattern binds l and r directly. And the result follows normal precedence only because the tree was built that way; the evaluator just follows the structure.
3Following One Evaluation Step by Step
It helps to trace the first example. eval(Add(Num 2, Mul(Num 3, Num 4))) matches the Add case, so it calls eval on Num(2), which returns 2, and eval on the Mul. The Mul case calls eval on Num(3) and Num(4), returning 3 and 4, and multiplies them to 12. Back in the Add case, 2 + 12 gives 14.
7 messages in order. Play them, or step through them one at a time.
4Adding a Guard for Multiplication by Zero
A guard is a when clause that adds a condition to a pattern. Patterns can also be nested: Mul(Num(int z), Expr r) matches only a Mul whose left side is a Num, and binds that number to z. With a guard we can skip evaluating the right side when the left side is zero.
Notice why the first version fails. Cases are tried from top to bottom, and the general Mul case already matches every Mul, so the guarded case could never run. The compiler calls this domination and rejects it. Placing the specific case first fixes it, and the general case still keeps the switch exhaustive, because a guarded case never counts towards exhaustiveness on its own. On Java 22 and later, the unused variable can be written as _: case Mul(Num(int z), _) when z == 0 -> 0.
5Extending the Model
The real strength of this design shows when we add a node type. Suppose we add Neg for negation.
The compiler points to every switch over Expr that needs a new case, such as eval, a pretty printer or a simplifier. With a default branch we would lose this help, which is why switches over sealed types are best written without one.
6Follow-up questions
Why use a switch instead of an eval() method on each record?
Both work. Methods on each record are natural when the set of operations is fixed and types are added often. A switch is natural when types are fixed and operations are added often, such as evaluating, printing, simplifying and type checking, because each operation stays in one place. Sealed types make the switch approach safe.
What happens if the evaluator receives null?
A switch over a null value throws NullPointerException, as switches always did, unless it has an explicit case null. For an expression tree, rejecting null is usually right, ideally at construction, for example with a compact constructor in each record that calls Objects.requireNonNull.
Could deep trees cause problems?
Yes. The evaluator is recursive, so a very deep tree, such as one built from a long chain of additions, can throw StackOverflowError. For untrusted input, limit the depth while parsing, or evaluate with an explicit stack.
7Conclusion
In this answer, we wrote the evaluator as a single switch expression with one record pattern per node type, recursing into the children of Add and Mul. Because Expr is sealed, the switch needs no default and the compiler checks that every type is covered. Record patterns removed the accessor calls, nested patterns and a when guard let us short-circuit multiplication by zero, and we saw that the guarded case must come before the general Mul case, or the compiler rejects it as dominated.
Open with
I would write eval as a single switch expression over the Expr. The first case is case Num(int v) arrow v. The second is case Add(Expr l, Expr r) arrow eval(l) plus eval(r), and the third is the same for Mul with multiplication.
Then, if they want more
That is the whole evaluator. The record patterns are doing two jobs: they test the type and they bind the components, so I never call accessors or cast. There is no default, because Expr is sealed with exactly Num, Add and Mul, all records, so the compiler can prove the switch is exhaustive.
That also means if someone adds a Neg or Sub to the permits list, every switch over Expr stops compiling until it handles the new type, which I see as a feature, so I deliberately avoid a default.
For the optimisation, I can nest patterns and add a guard: case Mul(Num(int z), Expr r) when z equals zero arrow zero, which skips evaluating the right side. The important detail is order.
That case must come before the general Mul case, because cases are tried top to bottom and the general one would match everything first; the compiler actually rejects the wrong order as a dominated case label. On Java 22 or later I would write the unused r as an underscore. For deep untrusted trees I would also think about recursion depth.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 21, Java 22
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Use Java 21 record patterns and switch to write an evaluator for:": https://scrivio-interview-library.netlify.app/java/java-versions/90f1b77492/