
🧑🏫 Java 21 Pattern Matching with switch and when Clauses
🗼🎭✨ Featuring the Glamorous World of Paris Cabarets
In Java, you can combine pattern matching in switch statements with guards,
which are additional when clauses used to refine the conditions for a match. This is known as a guarded pattern label.
A guard is simply a Boolean expression that must evaluate to true for the case to apply, after the pattern itself has matched.
🎩 Classic Approach (Pre-Pattern Matching)
Let’s say we’re modeling performers in a Parisian cabaret. We want to treat performers with short stage names differently.
💃 Modern Approach with when Clause
With pattern matching and when, we can make this more elegant and expressive:
🪄 What's Happening Behind the Curtain?
🟣 case String name when name.length() == 1
This matches if the performer is a String and the name has exactly one character – perhaps a mysterious cabaret star named “Z”.
🟣 case String name
This catches any other performer names that are still String, but longer than one character.
🟣 default
Handles anything that’s not a String – perhaps an object representing a light technician or a sound engineer.
🎭 Syntax Breakdown: p when e
A guarded pattern label follows this format:
🟣 The pattern (p) declares variables you can use inside the guard expression (e).
🟣 The guard (when) checks an additional condition.
🟣 If both the pattern and the guard match, the corresponding block executes.
📝 Final Thoughts
Using when clauses in switch makes your logic:
🟣 More concise
🟣 Easier to read
🟣 And way more expressive, just like a night at the Moulin Rouge 🌹