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
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