Explain the working principle of the copy method in a data class, considering the presence of fields inside the class.
sobes.tech AI
Answer from AI
The copy method in Kotlin data classes creates a new object by copying all fields of the original object, but allows you to modify some fields during copying. This is convenient for creating similar objects with minor differences without manually copying all properties.
If the class has fields, they are copied by value when calling copy. For primitive and immutable types, this is simply copying the values. If a field is a mutable object (e.g., a list), then a reference to this object is copied, not a deep copy. Therefore, when working with mutable fields, you need to be careful to avoid unintended shared state.
Example:
data class User(val name: String, val age: Int, val tags: MutableList<String>)
val user1 = User("Alice", 30, mutableListOf("admin"))
val user2 = user1.copy(age = 31)
user2.tags.add("editor")
println(user1.tags) // Will output ["admin", "editor"], since the list is shared
Thus, copy creates a shallow copy of the object, not a deep one. If deep copies are needed, they must be implemented manually.