Let's say I have an instance of a class and I want to duplicate and save the current state of the item, is there a way to do it without using the copy() method? If I just save the class instance somewhere in a variable, then its state changes too when the state of the original one changes, but I don't want that to happen. Does someone have an idea of how I can save the current class instance without it ever being mutated, so that whenever I want to use it again, I want the class instance to be exactly the same as when I saved it?
CodePudding user response:
The best way to make a copy of a case class
is to use copy
. If that is not acceptable (for whatever reason) then you have to create a new instance of the case class
with the same values.
But you only have this problem because you are using a mutable value in a class
. It is much, much better to keep data classes immutable so that you know that the values won't change under your feet. If you need to change the values, create a new instance with different values and use that, leaving the original untouched.
It take a while to learn to code in a functional way without mutable values, but it is worth the effort!