I have data class. For example:
data class Test(
val data: String,
val data2: String
)
Suppose I have a need to change one of the parameters of my data class. For this I will write the following code:
var test = Test(data = "data", data2 = "data2")
test = test.copy(data = "new_data")
But at the same time, I can make a parameter var
and change it directly:
data class Test(
var data: String,
val data2: String
)
var test = Test(data = "data", data2 = "data2")
test.data = "new_data"
Which method is better to use? Suppose that my data class can have a large number of parameters, will there be any problems in this case when using copy()
.
Please, help me.
CodePudding user response:
Depends how you're using the class.
I find it's more common to be using data classes to represent the "latest state" of something, in which case you do not want to be using var
with it, because that is error-prone. It prevents you from comparing old and new data, using the class in Sets and as Map keys, etc.
If they hold a representation of ongoing state (more common in games and simulations), var
might be applicable, in which case you'll find you rarely need the copy()
function. If you use copy()
in this case, you get a new copy without affecting the original.
CodePudding user response:
It depends on use case. I don't think there is globally preferred way.
In case you data class has to be immutable (using only vals) then go for test.copy(data = "newValue")
. Invoking copy will create new instance of data class
and use references of its attributes as input for newly created data class instance. Also original instance is still intact so it can be used for increment computations. This behavior can be nested
, in case that attribute is again data class.
Otherwise var
is also possibility -> updating same instance. But it may break things if instance is already in collection, used as key to cache etc.
So if you can go for immutable data class, I would prefer that with copy
- this apply for cases when updating is not happening too often and won`t consume to much memory.