javajava-15java-record

Set value to one of the property in Java 15 record


I am using Java 15 preview feature record in my code, and defined the record as follow

public record ProductViewModel
        (
                String id,
                String name,
                String description,
                float price
        ) {
}

In the controller level I have the below code

@Put(uri = "/{id}")
public Maybe<HttpResponse> Update(ProductViewModel model, String id) {
        return iProductManager.Update(id, model).flatMap(item -> {
            if(item == null)
                return Maybe.just(HttpResponse.notFound());
            else
                return Maybe.just(HttpResponse.accepted());
        });
    }

From the UI in the model the value of id is not passed, however, it is passed as a route parameter. Now I want to set the value in the controller level, something like

model.setid(id) // Old style

How can I set the value to the record particular property


Solution

  • You can't. Record properties are immutable.

    Wither methods

    What you can do however is add a wither to create a new record with same properties but a new id:

    public record ProductViewModel(String id,
                                   String name, 
                                   String description,
                                   float price) {
    
        public ProductViewModel withId(String id) {
            return new ProductViewModel(id, name(), description(), price());
        }
    } 
    

    In the future, Java records may get built-in wither methods. See JEP 468: Derived Record Creation (Preview), updated 2024-04. See video presentation by Nicolai Parlog, 2024-04.