record Person(String name, int age) {}
if (obj instanceof Person person) {
System.out.println("Name: " + person.name());
}
Now let’s look at a more traditional example. Geometric shapes are a classic way to prove, how closed work with records and especially clear. The elegance of this combination is evident in the expressions of the switches (introduced in Java 17), which allows you to write a brief, type – secure code that resembles algebraic data types in functional languages:
sealed interface Shape permits Rectangle, Circle, Triangle {}
record Rectangle(double width, double height) implements Shape {}
record Circle(double radius) implements Shape {}
record Triangle(double base, double height) implements Shape {}
public class RecordPatternMatchingExample {
public static void main(String() args) {
Shape shape = new Circle(5);
// Expressive, type-safe pattern matching
double area = switch (shape) {
case Rectangle r -> r.width() * r.height();
case Circle c -> Math.PI * c.radius() * c.radius();
case Triangle t -> t.base() * t.height() / 2;
};
System.out.println("Area = " + area);
}
}
Here, Shape
Type is sealed interface, only allows Rectangle
,, Circle
and Triangle
. Because this set is closed, the switch is exhausting and requires no starting branch.
Using records as data transfer objects
Records excel as data transfer objects (DTOS) in modern API designs such as Rest, Graphql, GRPC or Inter -Service Communication. Their brief syntax and built – in equality, records are ideal for mapping between layers of service. Here is an example: