Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 40 / 68

Shallow Copy vs. Deep Copy

In this lesson you will learn the difference between a shallow and a deep copy in Kotlin, so you can avoid bugs caused by unintentionally shared data. This is for anyone searching for "Kotlin shallow copy deep copy".

Assigning a Kotlin class instance to another variable actually copies a reference to the same object. That is the shallow-copy situation for classes, and changing one of them affects the other.

In the sample code, val shallow = original makes shallow point at the same Address instance as original. So setting shallow.city = "Osaka" also changes what original.city prints.

A common stumbling block for beginners is the bug where "I copied it, but the original changed too". Whenever you work with reference-type variables you need to keep this shallow-copy behaviour in mind.

In real-world development, when you want genuinely independent data, a data class's .copy() method duplicates an instance easily.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)