🏷 Records
4 patterns
Topic: Records
All Java patterns related to Records — java.evolved
Language
Compact canonical constructor
Old
public record Person(String name,
List<String> pets) {
// Full canonical constructor
public Person(String name,
List<String> pets) {
Objects.requireNonNull(name);
this.name = name;
this.pets = List.copyOf(pets);
}
}
Modern
public record Person(String name,
List<String> pets) {
// Compact constructor
public Person {
Objects.requireNonNull(name);
pets = List.copyOf(pets);
}
}
hover to see modern →
JDK 16+
learn more →
Language
Record patterns (destructuring)
Old
if (obj instanceof Point) {
Point p = (Point) obj;
int x = p.getX();
int y = p.getY();
System.out.println(x + y);
}
Modern
if (obj instanceof Point(int x, int y)) {
IO.println(x + y);
}
hover to see modern →
JDK 21+
learn more →
Language
Records for data classes
Old
public class Point {
private final int x, y;
public Point(int x, int y) { ... }
public int getX() { return x; }
public int getY() { return y; }
// equals, hashCode, toString
}
Modern
public record Point(int x, int y) {}
hover to see modern →
JDK 16+
learn more →
Errors
Record-based error responses
Old
// Verbose error class
public class ErrorResponse {
private final int code;
private final String message;
// constructor, getters, equals,
// hashCode, toString...
}
Modern
public record ApiError(
int code,
String message,
Instant timestamp
) {
public ApiError(int code, String msg) {
this(code, msg, Instant.now());
}
}
hover to see modern →
JDK 16+
learn more →