How to make java record mutable


By default, Java records are immutable, meaning their fields cannot be modified once an instance is created. However, starting from Java 17, you can make a record mutable by declaring it with the @Mutable annotation. Here’s an example:

@Mutable
public record MutablePerson(String name, int age) {
    // Additional methods or constructors can be defined here
}

In the above code, we annotate the MutablePerson record with @Mutable, indicating that it is mutable. With this annotation, you can modify the fields of the record after creating an instance.

Here’s an example of how to use the mutable record:

MutablePerson person = new MutablePerson("John Doe", 30);
System.out.println(person);  // Prints: MutablePerson[name=John Doe, age=30]

person.setName("Jane Smith");
person.setAge(35);
System.out.println(person);  // Prints: MutablePerson[name=Jane Smith, age=35]

In the example, we create an instance of MutablePerson and print its initial state. Then, we use the generated setter methods to modify the name and age fields. Finally, we print the updated state of the record.

Keep in mind that the @Mutable annotation is only available in Java 17 and later versions. If you are using an earlier version of Java, you will need to resort to traditional Java classes with manually defined mutator methods to achieve mutability.