• 🗼 Pattern Matching for switch Expressions

    – With Parisian Flair

    A switch statement in Java directs control flow based on the value of a selector expression. In earlier versions of Java, the selector expression had to be of certain types — such as int, short, byte, char, String, or an enum constant. Notably, types like long, float, double, and boolean were not and are still not permitted in a switch.

    🚀 What's New?

    With the introduction of pattern matching for switch (as detailed in JEP 441), Java now allows:

    🟣 Selector expressions of any reference type or int

    🟣 case labels that use patterns, including type patterns

    This enhances flexibility and makes code more concise, especially when working with type hierarchies.

    ⚠️ Still not allowed as selector expressions: long, float, double, boolean

    🏛️ Example with Paris Monuments

    Let’s model some famous Parisian landmarks:

    🧓 Before Java 21: Verbose instanceof

    Traditionally, if you wanted to perform actions based on the type of Monument, you'd use instanceof checks:

    ✨ Java 21+ Pattern Matching with switch Expression

    Let’s refactor the same logic using a pattern matching switch expression:

    🧭 Same with a switch Statement

    You can also use pattern matching in a classic switch statement format:

    📌 Summary

    broken image

    Java is evolving toward a more expressive and safer language, and this pattern matching feature is a major step—ideal even for expressing the grandeur of monuments like the Eiffel Tower or the Louvre.