0Pricing
Kotlin Academy · Lesson

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

  1. Data Class Basics: Auto-generated Methods
  2. Copying with copy() and Partial Overrides
  3. Destructuring Declarations with componentN
  4. Data Classes in Collections and as Map Keys
← Back to Kotlin Academy