Sobes.tech
Junior — Middle

What is the difference between creating a deep copy of an object and a shallow copy?

sobes.tech AI

Answer from AI

A shallow copy creates a new object but only copies references to nested objects, not the nested objects themselves. This means that changes in nested objects will reflect in the copy.

A deep copy creates a new object and recursively copies all nested objects, so the copy is completely independent of the original.

Example in Kotlin:

data class Person(var name: String, var address: Address)
data class Address(var city: String)

val original = Person("Ivan", Address("Moscow"))
val shallowCopy = original.copy() // copy with the same Address object
val deepCopy = original.copy(address = Address(original.address.city)) // create a new Address

shallowCopy.address.city = "Saint Petersburg"
println(original.address.city) // will output "Saint Petersburg" — the original has changed

deepCopy.address.city = "Novosibirsk"
println(original.address.city) // will remain "Saint Petersburg" — deepCopy is independent
What is the difference between creating a deep copy… - sobes.tech