Kar

Kar started this conversation 4 weeks ago.

0

1

java

How can Java 21’s combination of Records, Pattern Matching for instanceof, and Sealed Classes improve type safety and reduce boilerplate in class hierarchies?

New Java features introduced between Java 15–21 make expressing tagged unions and data classes much cleaner. This Q&A explains how to leverage them together.

Digiaru

Posted 4 weeks ago

A: • Records let you define simple, immutable data classes quickly: java Copy code public record Person(String name, int age) { } Automatically includes equals(), hashCode(), toString() and a canonical constructor. • Sealed classes (Java 15+) allow you to declare restricted class hierarchies: java Copy code public sealed interface Expr permits Add, Sub, Mul { } That gives the compiler knowledge of all possible implementations. • Pattern matching in instanceof (Java 16–17+) makes type-checks concise: java Copy code if (expr instanceof Add add) { // work with add.left() etc. } • Combined with switch-of-patterns (preview in Java 21), you can write exhaustive, type-safe algebraic-style handlers: java Copy code switch(expr) { case Add a -> …; case Sub s -> …; case Mul m -> …; } These features together enable expressive data-oriented modeling with no boilerplate—no manual getters, sealed-class validation, or visitor patterns. As summed up in Java 21 review: this trio works seamlessly to eliminate boilerplate, ensure type safety, and simplify code for domain logic.  Tags: Java 21, record, sealed classes, pattern matching, boilerplate