Sub topic 9
Sharing one switch case across several patterns
This chapter assumes you know switch expressions, sealed interfaces, records, and the unnamed variable _ from the earlier chapters. You should also be comfortable with type patterns (Circle c) and record patterns (Line(Point a, Point b)).
The problem: copy-pasted case bodies
Suppose you model UI events with a sealed interface and want to route each event to a subsystem. Two of the events go to the same place. Before Java 22, you had to repeat the body:
sealed interface Event permits Click, KeyPress, Scroll, Resize {}
record Click(int x, int y) implements Event {}
record KeyPress(char key, boolean shift) implements Event {}
record Scroll(int delta) implements Event {}
record Resize(int width, int height) implements Event {}
class OldRouter {
static String route(Event e) {
return switch (e) {
case Click c -> "input";
case KeyPress k -> "input";
case Scroll s -> "viewport";
case Resize r -> "layout";
};
}
}Each of those case labels declares a variable (c, k, s, r) that the body never reads. The two "input" branches are identical, but you could not merge them. The compiler rejected a label like case Click c, KeyPress k -> because it could not decide what c and k should mean in a body that runs for either type.
The rule: several patterns, no named bindings
Java 22 (JEP 456) lets one case label list several patterns, separated by commas, as long as none of them declares a named pattern variable. You can use unnamed pattern variables (Type _), the unnamed pattern (_), or patterns that have no binding at all.
sealed interface Event permits Click, KeyPress, Scroll, Resize {}
record Click(int x, int y) implements Event {}
record KeyPress(char key, boolean shift) implements Event {}
record Scroll(int delta) implements Event {}
record Resize(int width, int height) implements Event {}
public class Router {
static String route(Event e) {
return switch (e) {
case Click _, KeyPress _ -> "input";
case Scroll _ -> "viewport";
case Resize _ -> "layout";
};
}
public static void main(String[] args) {
System.out.println(route(new Click(3, 4)));
System.out.println(route(new KeyPress('a', false)));
System.out.println(route(new Scroll(-120)));
System.out.println(route(new Resize(800, 600)));
}
}Running this prints input, input, viewport, and layout, one per line.
The reason for the rule is simple. A body that is shared between alternatives can only use names that exist in every alternative. A named binding would exist in only one of them. Java avoids the problem by forbidding the names. Writing _ is also a promise to the reader that the body does not depend on the matched value.
What the compiler accepts and rejects
| Label | Allowed? | Why |
|---|---|---|
| `case Click _, KeyPress _ ->` | Yes | Both are unnamed pattern variables. |
| `case Click(_, _), KeyPress(_, _) ->` | Yes | Record patterns whose components are all unnamed patterns. |
| `case Click(int _, int _), Scroll _ ->` | Yes | Unnamed pattern variables nested in a record pattern. |
| `case Click c, KeyPress _ ->` | No | `c` is a named binding. |
| `case Click(int x, _), KeyPress _ ->` | No | `x` is a named binding inside a record pattern. |
| `case Click(var x, _), Click(_, var y) ->` | No | Named bindings, even if they have different names. |
The compiler reports an error at the first named binding, not at the comma. The fix is either to rename the binding to _ or to split the label into separate cases.
How the match proceeds
A switch checks its labels from top to bottom. A label with several patterns matches if any one of its patterns matches. Evaluation inside a label goes left to right, and the first success selects the body.
For a switch that is exhaustive over a sealed hierarchy, the last branch of the diagram is unreachable in practice. The compiler checks this at compile time. The MatchException only appears if the hierarchy changes after compilation, for example when a new permitted subtype is added in a separately compiled library.
Multi-pattern cases with record patterns
Multi-pattern labels become more useful when the patterns look inside records. Here a box holds a ball, and several shapes of nesting share a body.
sealed interface Ball permits RedBall, BlueBall, GreenBall {}
record RedBall() implements Ball {}
record BlueBall() implements Ball {}
record GreenBall() implements Ball {}
record Box(Ball ball) {}
public class Boxes {
static String label(Box box) {
return switch (box) {
case Box(RedBall _), Box(BlueBall _) -> "warm or cool";
case Box(GreenBall _) -> "natural";
};
}
public static void main(String[] args) {
System.out.println(label(new Box(new RedBall())));
System.out.println(label(new Box(new BlueBall())));
System.out.println(label(new Box(new GreenBall())));
}
}Without multi-pattern labels, the red and blue cases would need separate bodies. The compiler also checks exhaustiveness here. The three Ball subtypes are covered inside Box, so no default is needed.
A record pattern with only unnamed components is close to a type pattern. Click(_, _) and Click _ both match any Click. The difference is that the record pattern also tells the reader the arity of the record, and it can be extended later with a real component pattern such as Click(int x, _) without a restructure. The type pattern is shorter and does not break if the record gains a component. Choose the type pattern when you mean "any Click", and the record pattern when the shape of the record is part of the point.
Mixing shared and individual cases
A switch can combine multi-pattern labels with ordinary labels that do use named bindings. Only the shared label is restricted.
sealed interface Event permits Click, KeyPress, Scroll, Resize {}
record Click(int x, int y) implements Event {}
record KeyPress(char key, boolean shift) implements Event {}
record Scroll(int delta) implements Event {}
record Resize(int width, int height) implements Event {}
public class Mixed {
static String describe(Event e) {
return switch (e) {
case Click(int x, int y) -> "click at " + x + "," + y;
case KeyPress(char k, _) -> "key " + k;
case Scroll _, Resize _ -> "layout change";
};
}
public static void main(String[] args) {
System.out.println(describe(new Click(1, 2)));
System.out.println(describe(new KeyPress('q', true)));
System.out.println(describe(new Scroll(5)));
System.out.println(describe(new Resize(10, 20)));
}
}The first two cases need the data, so they bind it. The last case does not need any, so it groups two types. This is the typical shape of real code: the data-carrying cases stay separate, and the "everything else of this kind" cases are merged.
Ordering, dominance, and exhaustiveness
Merging patterns does not change the rules that apply to ordinary pattern labels.
- Dominance. A pattern is dominated if an earlier label already matches everything it could match. Each pattern in a multi-pattern label is checked against all earlier labels. If you write
case Event _ ->first, every later case is a compile error. - Redundancy inside a label. Listing a pattern that an earlier pattern in the same label already covers is also reported as an error, so
case Click _, Click(_, _) ->does not compile. - Exhaustiveness. A switch expression over a sealed type must cover every permitted subtype. A multi-pattern label contributes all its patterns to that coverage. If you later add a fifth record to
Event, every switch likeroutestops compiling until you handle it. That is the main reason to prefer an exhaustive pattern switch over adefaultbranch. Adefaultwould silently absorb the new type into whichever behavior you wrote for "everything else".
A merged label that ends in a catch-all hides the benefit. Compare these two:
sealed interface Event permits Click, KeyPress, Scroll {}
record Click(int x, int y) implements Event {}
record KeyPress(char key) implements Event {}
record Scroll(int delta) implements Event {}
public class Exhaustive {
static boolean isPointerEvent(Event e) {
return switch (e) {
case Click _, Scroll _ -> true;
case KeyPress _ -> false;
};
}
public static void main(String[] args) {
System.out.println(isPointerEvent(new Click(0, 0)));
System.out.println(isPointerEvent(new KeyPress('x')));
}
}If someone adds Resize to the sealed interface, this method fails to compile and forces a decision. Writing default -> false instead would compile and quietly classify Resize as not a pointer event.
The colon form and fall-through
Multi-pattern labels also work with the old case ...: syntax in switch statements. The same restriction applies, and there is one more rule about fall-through. Control may not fall through into a label that declares a named binding, because that binding would be uninitialized. Labels made only of unnamed patterns are safe to fall into.
sealed interface Shape permits Circle, Square, Triangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Triangle(double base, double height) implements Shape {}
public class Statements {
static void report(Shape s) {
switch (s) {
case Circle _:
System.out.println("round");
break;
case Square _, Triangle _:
System.out.println("has corners");
break;
}
}
public static void main(String[] args) {
report(new Circle(1));
report(new Square(2));
report(new Triangle(3, 4));
}
}New code should usually use the arrow form. It has no fall-through, so the issue does not arise.
Related label forms you may confuse with this feature
Several other case forms contain commas. They are separate features.
- Constant labels.
case 1, 2, 3 ->andcase MONDAY, FRIDAY ->have been valid since Java 14. They list constants, not patterns, and have no binding rules. case null, default ->. This combines thenulllabel withdefault. It is not a multi-pattern label, and you cannot combinenullwith type patterns in the same way.- Qualified enum constants. Since Java 21, a switch over a sealed interface can mix pattern labels with qualified enum constants. That is a different mechanism from the one in this chapter.
Common errors
- Leaving one name behind.
case Click _, KeyPress k ->fails because ofk. Check every pattern in the label, including nested ones. - Using
var xinside a shared label.var xis a named binding. Use_or a plainvar _is not needed: just write_as the component pattern. - Merging cases that need data. If the shared body needs a field, the cases are not really the same. Keep them separate and bind the field in each.
- Putting a broad type before a narrow one.
case Event _, Scroll _is an error becauseScrollis already covered byEvent. - Targeting Java 21. In Java 21 this syntax is a preview feature and needs
--enable-previewalong with--release 21. In Java 22 and later it is a standard feature.
Exercises
Exercise
Why does case Circle c, Square _ -> not compile, and what is the smallest change that fixes it?
Show answer
The label declares a named pattern variable c. A body shared between alternatives cannot rely on a name that exists for only one of them, so Java forbids named bindings in a multi-pattern label. Replace c with _ so the label becomes case Circle _, Square _ ->. This is valid when the body does not use the circle.
Exercise
Given sealed interface Animal permits Dog, Cat, Bird {} where all three are records, write a switch expression String sound(Animal a) that returns "bark" for Dog and "meow" for both Cat and Bird, with no default branch. What happens to this code if a fourth record, Fish, is added to the permits clause?
Show answer
return switch (a) { case Dog -> "bark"; case Cat , Bird _ -> "meow"; }; After Fish is added, the switch is no longer exhaustive, so the method fails to compile until a case for Fish is added. A default branch would have hidden this, because Fish would silently get whichever behavior the default returned.
Exercise
For the records Box(Ball ball) with sealed Ball permitting RedBall, BlueBall, and GreenBall, is this switch valid? case Box(RedBall _), Box(BlueBall _) -> 1; case Box(Ball _) -> 2; case Box(GreenBall _) -> 3;
Show answer
No. The second label Box(Ball _) matches every box, so it dominates the third label. The Box(GreenBall _) case can never be reached, and the compiler reports it as an error. Put the specific Box(GreenBall _) case before Box(Ball _), or remove the third case.