Java's sealed classes can break your API without a compile error

Java sealed classes and exhaustive pattern matching

Java 17's sealed classes enable exhaustive pattern matching, letting the compiler verify that all subtypes are handled. But adding a new subtype to a sealed interface is a breaking change for consumers, and if they aren't recompiled, the error only surfaces at runtime as a MatchException. The author concludes sealed types work best inside a component, not in public APIs, and points to a JDK proposal that makes exactly this mistake.

So even if you were hoping that using sealed classes would statically ensure that you update all consumers when a new case is added, this is not the case unless you recompile everything.
  1. shepherdjerred

    I love how far Java has come. I still prefer TypeScript since I do a lot of frontend work and prefer to use the same language across the stack.

    With the said, you can do exhaustive pattern matching in TypeScript! https://github.com/gvergnaud/ts-pattern

  2. armchairhacker

    Java also has recursive patterns and (maybe still in preview) literal patterns: `switch (x) { case A(B(true, var c)) -> f(c); }`

  3. another_twist

    Took me a while to get used to sealed and I didn't quite see the use. But AI seems to love it for Java so I gave it a go and now I get it. Its like a really good access control mechanism esp if you use DI and want to deprecated some stuff. Apart from ofcourse the pattern matching - which comes in handy for event driven messages where payload shape changes.

  4. timshel2

    Scala punching the air rn

  5. panny

    I don't think you need those switch defaults with the sealed types. I didn't check with a compiler, but I think those are unnecessary.

  6. Larrikin

    Java continues to try and catch up to Kotlin

    https://kotlinlang.org/docs/sealed-classes.html

    I didn't mind Java when the comparisons were to C++, Ruby, and Python. I can not find a reason to go back after Scala (which seemed to fail due to being indiscriminate) and especially Kotlin

More from this day

2026-10-18