9.2 Copying a data class
If we use immutability, as talked some chapters ago, we’ll find that if we want to change the state of
an object, a new instance of the class is required, with one or more of its properties modified. This
task can be rather repetitive and far from clean. However, data classes include the
copy()
method,
which will make the process really easy and intuitive.
For instance, if we need to modify the temperature of a
Forecast
, we can just do:
1
val f1 = Forecast(Date(), 27.5f, "Shiny day")
2
val f2 = f1.copy(temperature = 30f)
This way, we copy the first forecast and modify only the
temperature
property without changing
the state of the original object.
31
9 Data Classes
32
Do'stlaringiz bilan baham: |