if you've got a `class` with a lot of state, and y...
# getting-started
y
if you've got a
class
with a lot of state, and you would like to clone it and only change one
val
- how should this be done? are you expected to make it into a
data class
and use the generated
copy
impl? or move all the state into a private primary constructor? or...?
g
Yes
data class
and using
copy()
is the right way to do it
➕ 1
y
so
data class
is in no way an indication of the class being a "plain old data" - it's just opt-in for the various derived impls such as
copy
and
toString
?
👍 2
j
If you're expecting the states to change independently fairly often then maybe keeping them separate is a better idea
m
You can also add your own
copy
function to any class you want.
c
If you only want to change one
val
, and it's always the same
val
, you can add a method to the class that creates a new instance with only the one modification, copying the rest. One example of where this is useful is when running simulations, like the Game of Life. I add a method called
getNextState()
in order to make a new instance that has many copied values and a small subset of changed values. I have a hunch that this might be closer to what you're looking for!
m
Yeah, dedicated change functions related to the domain is often better than a copy function. It gives a name to what you are trying to do when you call it.
s
kotlinx.datetime defines a bunch of these, if you'd like some standard library examples.
Copy code
fun YearMonth.minusMonth(): YearMonth
https://kotlinlang.org/api/kotlinx-datetime/kotlinx-datetime/kotlinx.datetime/minus-month.html