• 🎓 Java: switch Expressions with yield

    Featuring French Poets 🇫🇷📚

    In Java, you can use case L: labels in switch expressions. When you do this, the block of code to the right of the label is called a switch labeled statement group.

    Here’s an example using a switch expression with famous French poets:

    In this code:

    🟣 We're using a switch expression to return a value.

    🟣 The yield keyword is used to produce a value from a case branch.

    🟣 The System.out.println(...) calls are just here to simulate additional logic in each case.

    This design allows switch expressions to return values clearly and concisely. It's also useful for pattern matching and decision structures.

    🧠 Important Note on yield

    🟣 yield is only used in switch expressions, not switch statements.

    🟣 In contrast, switch statements use break to prevent fall-through.

    🟣 If you forget to include a yield or break in traditional case L: syntax, you may introduce unintended fall-through behavior.

    💡 Prefer case L -> for Clarity

    Java also supports a more concise and modern syntax: case L ->. This is safer and reduces the risk of fall-through. If you need to run multiple statements, wrap them in a block and use yield explicitly:

    📘 Enum for the Poets

    Here’s how you might define the Poet enum:

    ✅ Summary

    🟣 Use yield when working with switch expressions to return values.

    🟣 Use case L -> instead of case L: when possible to make your code safer and clearer.

    🟣 When handling more complex logic in a case, use a block {} and a yield inside.