Java 17 introduced sealed classes, which allow developers to explicitly list the permitted sub-types of an interface or class. This feature enables exhaustive pattern matching, allowing the compiler to verify that all cases are covered in a switch expression without requiring a default clause. For example, a sealed interface `SealedType` with sub-types `TypeA` and `TypeB` can be used in a switch expression that only handles those two cases, eliminating the need for a default case.
However, this introduces a new type of breaking change: adding a new sub-type to a sealed class will break consumers if they do not recompile their code. If a consumer is not recompiled, a runtime exception (such as `MatchException`) may occur when the new case is triggered. This is particularly problematic when sealed types are exposed in public APIs, as separate compilation can lead to undetected failures.
Sealed types are most useful within the implementation of a single component, where all code is recompiled together. When used across module boundaries, they may introduce new ways to break code that are only detectable at runtime. Developers should carefully consider whether sealed types are appropriate for public APIs.
Source: Hacker News · Summarized by HeadlinesBriefing