Sobes.tech
Junior — Middle

Can you explain the purpose of the copy method in Kotlin data class and how to use it?

sobes.tech AI

Answer from AI

The copy method in Kotlin data class is used to create a new object based on an existing one, while allowing some properties to be changed without affecting the original object. This is convenient for working with immutable objects when you need to get a similar object with minor modifications.

Example:

data class User(val name: String, val age: Int)

val user1 = User("Ivan", 30)
val user2 = user1.copy(age = 31) // Create a new object with a changed age

println(user1) // User(name=Ivan, age=30)
println(user2) // User(name=Ivan, age=31)

Thus, copy makes it easy to clone objects with modifications while maintaining the immutability of the original data.