
🧑🍳 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:
If we switch on that enum and cover all known values, there’s no need for default:
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:
🔴 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:
🚫 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:
🍽️ 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!