0Pricing
Java Academy · Lesson

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

  1. Pattern Matching for instanceof
  2. Record Patterns
  3. Nested Record Patterns
  4. Patterns in switch
← Back to Java Academy