Immutability · Topic 5 of 6
Withers (copy with a change)
Definition​
A "wither" is a method that returns a copy of an immutable object with one value changed, for example withEmail(...). It gives you the convenience of updating without making the object mutable.
Example code​
Changing one field by creating a modified copy
record User(String name, String email, int age) {
User withEmail(String newEmail) { return new User(name, newEmail, age); }
User withAge(int newAge) { return new User(name, email, newAge); }
}
class Demo {
public static void main(String[] args) {
User original = new User("Asha", "asha@old.com", 30);
User updated = original.withEmail("asha@new.com").withAge(31);
System.out.println(original); // unchanged
System.out.println(updated); // the modified copy
}
}
// Output:
// User[name=Asha, email=asha@old.com, age=30]
// User[name=Asha, email=asha@new.com, age=31]
Finished this page? Track your progress (saved only in your browser).