Course contentsShow
← Java
Lesson 613 of 2,87014. EnumerationsFree lesson

Pattern Matching with Enums in Switch (Java 21+)

Explore advanced pattern matching capabilities when switching on sealed types containing enums.

Pattern Matching with Enums in Switch (Java 21+)

What you'll learn: How to use advanced pattern matching in switch statements when working with sealed types that contain enums, introduced in Java 21.

The Core Idea

Java 21 extends pattern matching in switch statements to work seamlessly with enums, especially when they're part of sealed hierarchies. While traditional enum switches require listing each constant explicitly, pattern matching allows you to deconstruct and test enum values more expressively, particularly when combined with sealed types (interfaces or classes that restrict which types can implement or extend them).

When you have a sealed type that includes enum variants, you can now pattern-match against both the type and its specific enum values in a single switch expression. This creates more readable, maintainable code when dealing with complex type hierarchies.

How It Works

Imagine you have a sealed interface with enum implementations. Pattern matching lets you write switches that test "Is this value an instance of X and does it equal constant Y?" in one smooth operation.

The compiler understands the complete set of possibilities (because the type is sealed and enums have fixed constants), so it can verify exhaustiveness—ensuring you've handled every case without needing a default branch.

Real-World Analogy

Think of sorting mail: instead of just checking "Is this a letter or package?" (type), you can simultaneously check "Is this a letter from California?" (type + specific property). Pattern matching with enums lets you inspect both layers at once.

When This Matters

This feature shines when modeling state machines, processing algebraic data types, or handling protocol messages where you need to distinguish both the category (sealed type) and specific variants (enum constants) simultaneously.

Key Takeaway: Pattern matching with enums in Java 21+ switch statements enables elegant handling of sealed type hierarchies containing enums, combining type testing and constant matching while maintaining exhaustiveness checking.