The copy Function

Immutable Updates

Data classes usually use val properties. To "change" one, create a modified copy with copy() and named arguments. The original stays untouched - this is how state is updated in Jetpack Compose and Redux-style architectures.

Example

data class Profile(val name: String, val city: String, val followers: Int = 0)

fun main() {
    val original = Profile("Rahul", "Chennai", 120)
    val moved = original.copy(city = "Bengaluru")
    val famous = moved.copy(followers = moved.followers + 1000)
    println(original)
    println(moved)
    println(famous)
}

Output

Profile(name=Rahul, city=Chennai, followers=120)
Profile(name=Rahul, city=Bengaluru, followers=120)
Profile(name=Rahul, city=Bengaluru, followers=1120)

copy is Shallow

Example

copy() copies references, not nested objects. A mutable list inside is shared between copies - another reason to prefer read-only List.

data class Playlist(val name: String, val songs: MutableList<String>)

fun main() {
    val a = Playlist("Gym", mutableListOf("Song A"))
    val b = a.copy(name = "Gym Copy")
    b.songs.add("Song B")
    println(a.songs)   // changed too!
    println(b.songs)
}

Output

[Song A, Song B]
[Song A, Song B]

Tip: Keep data classes immutable: val properties and read-only collections. Then sharing copies is always safe.