Part 1 · 1 chapters · ~8 min

The Type System

Classes, interfaces and inheritance, generics and erasure, records, sealed interfaces, pattern matching for instanceof and switch, enums with behaviour, Optional, nullability and its tools, and modelling a payment domain with algebraic data types.

3

Records, sealed types and patterns

code
public record Money(long minor, String currency) {
    public Money { if (minor < 0) throw new IllegalArgumentException("negative"); Objects.requireNonNull(currency); }
}
public sealed interface TransferResult permits Completed, Pending, Failed {}
public record Completed(String id, Money amount) implements TransferResult {}
public record Pending(String id, Instant since) implements TransferResult {}
public record Failed(String id, String reason) implements TransferResult {}

String message(TransferResult r) {
    return switch (r) {                                    // exhaustive: no default needed
        case Completed c -> "Sent " + c.amount().minor() / 100;
        case Pending p   -> "Pending since " + p.since();
        case Failed(var id, var reason) -> "Failed: " + reason;   // record deconstruction
    };
}
MODERN JAVA DATA MODELLING
records, sealed interfaces and pattern matching together
recordsImmutable data carriers: fields,constructor, equals, hashCode,toString generated.sealed interfacesA closed set of implementationsthe compiler knows about.pattern matchingswitch over types withdeconstruction; the compilerchecks exhaustiveness.genericsType-safe collections and APIs;erased at run time.OptionalA return type for "maybe absent",not a field type.enumsFull classes with fields andmethods; great for state machines.
swipe the figure sideways, or tap expand for full screen
1/6
records
record Money(long minor, String currency) {} gives an immutable value type in one line, with a compact constructor for validation.
immutable data in one linevalidate in the compact constructor