Video in progress
What happens to pattern switches when a new subtype is added to a sealed interface, and why is it better not to write default?
Without default, the compiler flags every switch that doesn't cover the new subtype as an error. With default, the new case quietly falls into it, and the bug only shows up at runtime.
📖 Answer
sealed interface Payment permits Card, Cash, Transfer {}
BigDecimal fee(Payment p) {
return switch (p) {
case Card c -> c.amount().multiply(RATE);
case Cash c -> BigDecimal.ZERO;
case Transfer t -> FIXED;
}; // no default: exhaustive
}
Now you add QrPay and list it in permits. The result is a compile error: "the switch expression does not cover all possible input values". The compiler lists every place in the whole codebase where logic needs to be added, which is the main benefit of sealed.
If default -> BigDecimal.ZERO had been written, the fee for QrPay would silently be zero.
What happens at runtime? If the sealed hierarchy changes and the class with the switch isn't recompiled (for example, in another module/jar), a hidden check added by the compiler throws MatchException. An exhaustive enum switch compiled with the Java 21 javac throws that too; in older JDKs it was IncompatibleClassChangeError.
In practice:
- avoid
defaultin a switch over a sealed hierarchy; - all the subtypes must be in one module (or in one package if there are no modules): that's a requirement;
- a subtype must be
final,sealedornon-sealed.non-sealedopens the hierarchy up again and exhaustiveness is lost, so choose it deliberately.
Sign up to mark studied questions and save your progress.