Introduction to Java’s records: Simplified programming centered in Java

record Person(String name, int age) {}

if (obj instanceof Person person) {
    System.out.println("Name: " + person.name());
}

Now let’s consider a more traditional example. Geometric shapes are a classic way to demonstrate how interfaces sealed with records work, and make patterns coincidence especially clear. The elegance of this combination is evident in switching expressions (introduced in Java 17), which allows you to write a concise code and SAFE type 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, the Shape The type is a sealed interface, only allows Rectangle, Circleand Triangle. Because this set is closed, the switch is exhaustive and does not require a default branch.

Use of records such as data transfer objects

Records stand out as data transfer objects (DTO) in modern API designs such as rest, graphql, GRPC or communication between services. Its concise syntax and incorporated equality make the records ideal for mapping between service layers. Here is an example:

#Introduction #Javas #records #Simplified #programming #centered #Java

Leave a Reply

Your email address will not be published. Required fields are marked *