Video in progress
In Java 21, can a sealed interface and a pattern matching `switch` replace the Visitor pattern?
In many cases, yes. A sealed hierarchy and an exhaustive switch let you add a new operation without the accept/visit boilerplate, and when a new type is added the compiler points at every switch. If the hierarchy isn't closed, you still need Visitor.
📖 Answer
The classic Visitor:
interface ExprVisitor<R> { R visitNum(Num n); R visitAdd(Add a); }
interface Expr { <R> R accept(ExprVisitor<R> v); }
record Num(int v) implements Expr {
public <R> R accept(ExprVisitor<R> v) { return v.visitNum(this); }
}
// an accept for every type, a visitor class for every operation
The Java 21 version:
sealed interface Expr permits Num, Add, Mul {}
record Num(int v) implements Expr {}
record Add(Expr l, Expr r) implements Expr {}
record Mul(Expr l, Expr r) implements Expr {}
static int eval(Expr e) {
return switch (e) {
case Num n -> n.v();
case Add(Expr l, Expr r) -> eval(l) + eval(r);
case Mul(Expr l, Expr r) -> eval(l) * eval(r);
}; // no default: the compiler checks completeness
}
A new operation (print, simplify) is just a static method. A new type (Neg) is added to permits and the compiler flags every switch as "not exhaustive". You keep the safety Visitor gives you, with half the code.
When Visitor stays:
- the hierarchy is open (a library user can add their own type), so you can't use
sealed; - code running below Java 21 (pattern matching for switch and record patterns became final in Java 21);
- when you need complex double dispatch inside a type.
Note that if you add a default ->, the benefit of the completeness check is lost. Make it a habit not to write default on a sealed hierarchy.
Sign up to mark studied questions and save your progress.