Skip to the page

Types, errors and modern syntax · mid

Records, sealed types and pattern matching

Records are short immutable data classes. Sealed types list every allowed subtype, so a switch over them needs no default and the compiler finds missing cases.

The notes

What you must know

  • A record (final since Java 16) is a final class with private final fields, a canonical constructor, accessors named like the fields (id(), not getId()), and equals, hashCode and toString.
  • Validation goes in a compact constructor. Records can implement interfaces but cannot extend a class or add instance fields.
  • Good fits: DTOs, API requests and responses, events, value objects, map keys. Not a fit for JPA entities, which need mutable state and proxying.
  • Sealed (final since Java 17): sealed interface PaymentResult permits Success, Declined, Pending {}. Each permitted subtype must be final, sealed or non-sealed.
  • Permitted subtypes must be in the same module, or in the same package when there is no named module.
  • Pattern matching for switch and record patterns are final in Java 21. instanceof with a binding (e instanceof Captured c) is older.
  • With a sealed type the compiler knows every case, so no default is needed. Adding a new subtype breaks the build at every switch that misses it. An if-chain compiles silently and fails later.
  • Order matters: a guarded case must come before the unguarded one for the same type. A null selector throws NullPointerException unless there is a case null. Enum constants are fixed single instances with the same fields. Sealed subtypes (often records) can carry different data per case.

The red pen

Common traps: mistake → fix

  • Mistake: Records can replace JPA entities

    Fix: entities need a no-argument constructor, mutable state and proxies.

  • Mistake: A sealed switch needs a default

    Fix: not when all permitted subtypes are covered.

  • Mistake: Lombok and records are the same thing

    Fix: records are a language feature; Lombok generates code and needs an annotation processor.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is a record and what can it not do?
  2. What does sealed do and where would you use it in a backend?
  3. Rewrite this instanceof chain with a Java 21 switch. What happens when someone adds a new event type?
  4. Records or Lombok for DTOs?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview