Sub topic 9
Sharing one switch case across several patterns
This chapter assumes you know sealed interfaces, records, and switch expressions with type patterns. It also assumes you have met unnamed pattern variables (Type _) and the unnamed pattern (_) from the previous chapters. You need Java 22 or later.
The problem: duplicated branches
Suppose two shapes should produce the same result. Before Java 22, you wrote one case per type and repeated the body:
case Square s -> "has corners";
case Triangle t -> "has corners";Both branches declare a variable, s and t, that the body never reads. The result is duplicated code and two unused names.
Listing several patterns in one case
Java 22 lets a single case label hold a comma-separated list of patterns. The case runs if any one of them matches. The list is allowed only when no pattern in it declares a named binding variable. Unnamed pattern variables (Type _) declare no binding, so they qualify.
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 Describe {
static String describe(Shape s) {
return switch (s) {
case Circle _ -> "round";
case Square _, Triangle _ -> "has corners";
};
}
public static void main(String[] args) {
System.out.println(describe(new Circle(1.0)));
System.out.println(describe(new Square(2.0)));
System.out.println(describe(new Triangle(3.0, 4.0)));
}
}The program prints round, has corners, and has corners. The switch has no default branch. Because Shape is sealed and the two cases together cover Circle, Square, and Triangle, the compiler still checks exhaustiveness. If you add a fourth permitted type, this switch stops compiling until you handle it.
Why named bindings are not allowed
Consider case Square s, Triangle t. If the case matched a Square, then t would have no value. If it matched a Triangle, then s would have none. The compiler cannot give the body a variable that might be uninitialized, so it rejects the label.
| Case label | Allowed? | Reason |
|---|---|---|
| `case Square _, Triangle _` | Yes | No binding is declared. |
| `case Square s, Triangle _` | No | `s` would be unset when `Triangle` matches. |
| `case Square s, Triangle t` | No | Neither variable is always set. |
| `case Square s` | Yes | A single pattern may bind a name. |
If the body needs the matched value, use separate cases, or match on a common supertype and bind that.
Record patterns in a shared case
Each pattern in the list can be a record pattern, as long as every part of it is unnamed. The unnamed pattern _ is useful here because it ignores components you do not care about.
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 {}
record Pair(Shape first, Shape second) {}
public class PairCheck {
static boolean hasCircle(Pair p) {
return switch (p) {
case Pair(Circle _, _), Pair(_, Circle _) -> true;
case Pair(_, _) -> false;
};
}
public static void main(String[] args) {
System.out.println(hasCircle(new Pair(new Circle(1), new Square(2))));
System.out.println(hasCircle(new Pair(new Square(2), new Circle(1))));
System.out.println(hasCircle(new Pair(new Square(2), new Triangle(3, 4))));
}
}This prints true, true, and false. The first case matches when either component is a Circle. The final case, Pair(_, _), catches every remaining pair.
Gotchas
- Order and dominance. A pattern that matches everything an earlier label matches makes the later one unreachable, and the compiler reports that as an error. In
hasCircle,Pair(_, _)must come last. Placed first, it would dominate the other label. - Guards. A
whenguard applies to the whole label, so it is evaluated whichever pattern matched. Keep guards simple on multi-pattern labels. - Same behavior is the point. Only merge cases whose bodies really are identical. If the bodies might diverge later, separate cases are easier to edit.
Exercise
Why does case Circle c, Square _ -> "shape" fail to compile, and how can you fix it if the body does not use c?
Show answer
The label declares a named binding c. When Square matches, c would have no value, so Java rejects it. If the body does not use c, change it to case Circle _, Square _ -> "shape".
Exercise
Write a switch case label that returns true when a Pair has a Square in either position, ignoring the other component.
Show answer
case Pair(Square _, _), Pair(_, Square _) -> true;