How do you write an immutable class? Is a record fully immutable?
Short answer
An immutable class can't change once created: private final fields, no setters, a final class, and copies of changeable fields like List.
3 points to say:
- To "change" it, return a new object (
withX). - Threads can share it without locks.
- A record still needs
List.copyOffor a list inside.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.