Java sealed classes and exhaustive pattern matching

Java sealed classes prevent runtime errors but require recompiling to avoid breaking code.

6 cards · 50s · tap to begin

From · · 50s

Java sealed classes and exhaustive pattern matching

Java sealed classes prevent runtime errors but require recompiling to avoid breaking code.

In brief

Java sealed classes prevent runtime errors but require recompiling to avoid breaking code. Sealed classes ensure exhaustive pattern matching at compile time but break when new subtypes are added without recompiling. Originally reported by Neilmadden.

Java 17 sealed classes

Java 17 introduced sealed classes to explicitly list allowed sub-types of interfaces or base classes.

Sealed interface example

A sealed interface with records TypeA and TypeB allows switch expressions without default clauses.

Exhaustiveness checking

Sealed classes enable compile-time error detection for missing switch cases.

Adding new subtypes

Adding a new subtype to a sealed class breaks consumers without recompiling.

Runtime exception risk

Separate compilation causes runtime exceptions when new subtypes are added.

Internal vs public API

Sealed classes are most useful internally where recompiling everything is possible.

What it means

Sealed classes ensure exhaustive pattern matching at compile time but break when new subtypes are added without recompiling.

Read the original on Neilmadden

React

Sign in to react and comment.

Comments (0)

Life is short. Keep it sweet. Respect others' opinions and be kind!

    Recommended next

    More decks on java and related topics.