Records

Records are a feature introduced in Java 14. They are a new kind of class introduced to reduce boilerplate code for immutable data-carrying objects. Records provide a compact way to declare classes that are transparent holders for shallowly immutable data.

Here's a basic example of how you would define a record in Java.

public record Person(String name, int age) {
    // No need to explicitly declare fields, constructor, equals, hashCode, or toString
}

In this example, "Person" is a record that consists of two components: "name" and "age". When you define a record, the compiler automatically generates the following:

- Private final fields for each component (e.g., "name" and "age" in this case).

- A public constructor that initializes these fields.

- Getter methods for each component.

- An "equals()" method that compares the contents of two "Person" objects.

- A "hashCode()" method based on the contents of the record.

- A "toString()" method that displays the components' values.


Records can be used in various scenarios where you need lightweight data carriers, as representing data from a database, representing HTTP requests/responses, or carrying configuration settings.

Records are implicitly final and immutable. Once created, you cannot modify their state. However, if you need to create a new record with modifications, you can use the "with" keyword to create a new record instance with specified changes.

Person person = new Person("John", 30);
Person modifiedPerson = person.withAge(35);

This creates a new "Person" record with the same name as the original but with an age of 35.

Records help improve code readability, reduce boilerplate, and encourage immutability, which leads to more robust and maintainable code.

Nenhum comentário:

Postar um comentário

Internet of Things (IoT) and Embedded Systems

The  Internet of Things (IoT)  and  Embedded Systems  are interconnected technologies that play a pivotal role in modern digital innovation....