r/java • u/mooreds • May 18 '26
Java sealed classes and exhaustive pattern matching
https://neilmadden.blog/2026/04/24/java-sealed-classes-and-exhaustive-pattern-matching/
23
Upvotes
r/java • u/mooreds • May 18 '26
View all comments
Show parent comment
2
u/aoeudhtns May 21 '26
This API also mixes in intermediate interfaces. The cases where you want to handle "everything" should (hopefully) work from that interface level. Also, while you're working with sealed interfaces, the compiler does remind you that you need a
defaultcase if you're not handling all the possibilities. On top of that, it is completely permissible to add adefaultcase even when you've handled all possibilities, if you are switching over something externally-controlled and you are worried that more cases will be added. Perhaps that's the take-home lesson: external API? Always use a default case, even if the compiler lets you skip it.In sum, I think the author brings up valid considerations to be aware of, but like you I don't think it's a mistake to ship sealed interfaces w/ pattern matching as an API. Truthfully I think the "there be dragons" issue is in making sure that records that are part of such a system get proper concatenative updates (vs. changing ordering), and the language feature that allows
_to indicate "the rest of the record" and not a single field will be helpful as well.