Copying with copy() and Partial Overrides
Use copy() to create modified instances without mutating the original.
Immutable Updates with copy()
copy() creates a new instance of a data class with some properties modified. All unspecified properties retain their original values.
Basic copy()
Pass named arguments to override specific properties.
data class Person(val name: String, val age: Int, val city: String)
val alice = Person("Alice", 30, "Berlin")
val olderAlice = alice.copy(age = 31)
println(olderAlice) // Person(name=Alice, age=31, city=Berlin)All lessons in this course
- Data Class Basics: Auto-generated Methods
- Copying with copy() and Partial Overrides
- Destructuring Declarations with componentN
- Data Classes in Collections and as Map Keys