Patterns in switch
Combine sealed types and patterns.
Patterns in switch
Switch has grown from matching constants to matching patterns. Combined with sealed types and records, a switch can dispatch on type, destructure data, and guarantee completeness.
Type Patterns in switch
Each case can be a type pattern, binding a typed variable for that branch.
public class Main {
static String kind(Object o) {
return switch (o) {
case Integer i -> "int " + i;
case String s -> "string " + s;
default -> "other";
};
}
public static void main(String[] args) {
System.out.println(kind(42));
System.out.println(kind("hi"));
System.out.println(kind(3.14));
}
}All lessons in this course
- Pattern Matching for instanceof
- Record Patterns
- Nested Record Patterns
- Patterns in switch