• 🧑‍🍳 Exhaustiveness of switch Expressions

    — à la française 🇫🇷

    In Java, switch expressions must be exhaustive. That means they must cover all possible values of the expression being switched on. If not, the compiler won't be happy. Normally, you’ll need a default branch to handle all remaining cases.

    However, there’s a tasty exception 🍽️: if you're switching on an enum and you've listed all possible enum constants, then Java considers it exhaustive — no need for default, it adds one implicitly.

    Example with French Dishes: Enum Edition

    Let’s say we have a lovely enum representing some famous French dishes:

    enum PlatFrancais {
        RATATOUILLE, BOUILLABAISSE, COQ_AU_VIN
    }

    If we switch on that enum and cover all known values, there’s no need for default:

    String accompagnement = switch (plat) {
        case RATATOUILLE -> "Pain de campagne";
        case BOUILLABAISSE -> "Rouille et croûtons";
        case COQ_AU_VIN -> "Pâtes fraîches";
    };

    This is fine because the compiler knows all the PlatFrancais options and we covered them all.

    🧂 The Yield Rule: No Missing Ingredients!

    Every case in a switch must return a value using yield, unless it's a simple arrow -> form.

    Let’s see what happens when we forget the yield, like a chef who forgets the salt:

    String sauce = switch (plat) {
        case RATATOUILLE -> {
            System.out.println("Légumes mijotés");
            // ❌ ERROR! No yield in the block
        }
        default -> "Sauce inconnue";
    };

    🔴 This won’t compile. If you use a block ({ }) instead of the simple arrow (->), you must use yield.

    Same issue if you group cases but forget to yield for all of them:

    String vin = switch (plat) {
        case COQ_AU_VIN, BOUILLABAISSE -> {
            System.out.println("Accord mets et vins");
            // ❌ ERROR! Missing yield
        }
        default -> "Eau pétillante";
    };

    🚫 Illegal Jumps: No Escaping the Kitchen!

    Inside a switch expression, you can’t jump out with break, continue, or return. Java requires the switch to resolve to one single value, not an escape route.

    Here’s a forbidden move:

    platLoop:
    for (PlatFrancais plat : menu) {
        String dessert = switch (plat) {
            case RATATOUILLE -> "Tarte Tatin";
            case COQ_AU_VIN -> "Île flottante";
            default -> {
                continue platLoop; // ❌ ERROR! Illegal jump through a switch expression
            }
        };
    }

    🍽️ TL;DR: A switch expression is like a recipe. You must:

    🟣 Provide an ingredient (value) for each case.

    🟣 Use yield in blocks.

    🟣 Avoid jumping out mid-recipe!