
Pattern Label Dominance
— Paris Monuments Edition
In Java's enhanced switch with pattern matching, multiple case labels might match the selector expression. To ensure clarity and predictability, the switch block checks the labels in the order they appear.
The compiler will raise a compile-time error if it detects that a case label can never be reached because a previous one always matches first. This concept is called pattern label dominance.
Let’s explore this with a French twist! 🗼🖼️⛪
🚨 Example 1: Eiffel Tower dominates the rest
🧠 Explanation: The case Monument m matches all subclasses, including EiffelTower. So when the switch sees an EiffelTower, it already matches Monument, and will never reach the more specific case. That’s why the compiler says "label is dominated".
🚫 Example 2: Pattern labels also dominate constants
💡 Here, the pattern case Integer i already matches any number, so the specific constant cases 1889 and 2024 are never reached. The compiler complains again.
🎨 Example 3: Enum pattern dominance with the Louvre
Again, case MonumentColor c already catches everything in the enum, including WHITE. So the constant label is dominated.
✅ Guarded patterns do NOT dominate constants
Here’s the twist: guarded patterns (those with when) don’t dominate constant values.
🧠 Here, even though 300 is greater than 100, the compiler does not consider the guarded case (h > 100) as dominant. Guarded patterns are excluded from dominance checks for complexity reasons.
✅ Recommended Order for Case Labels
To avoid confusion and compiler errors, follow this ordering convention:
- Constants first (e.g. case 300)
- Guarded patterns next (e.g. case Integer h when h > 100)
- Generic patterns last (e.g. case Integer h)
🧾 Summary