Skip to content

Commit e0f58a7

Browse files
committed
chore: explain shallow copy for data classes
1 parent a0799c6 commit e0f58a7

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

docs/topics/data-classes.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,31 @@ val jack = User(name = "Jack", age = 1)
9999
val olderJack = jack.copy(age = 2)
100100
```
101101

102+
The `copy()` function creates a _shallow_ copy of the instance. In other words, it doesn't copy components recursively.
103+
As a result, references to other objects are shared.
104+
105+
For example, if a property holds a mutable list, changes made through the "original" value are also visible through the copy,
106+
and changes made through the copy are visible through the original:
107+
108+
```kotlin
109+
data class Employee(val name: String, val roles: MutableList<String>)
110+
111+
fun main() {
112+
val original = Employee("Jamie", mutableListOf("developer"))
113+
val duplicate = original.copy()
114+
115+
duplicate.roles.add("team lead")
116+
117+
println(original)
118+
// Employee(name=Jamie, roles=[developer, team lead])
119+
println(duplicate)
120+
// Employee(name=Jamie, roles=[developer, team lead])
121+
}
122+
```
123+
{kotlin-runnable="true" kotlin-min-compiler-version="1.3"}
124+
125+
As you can see, modifying the `duplicate.roles` property also changes the `original.roles` property because both properties share the same list reference.
126+
102127
## Data classes and destructuring declarations
103128

104129
_Component functions_ generated for data classes make it possible to use them in [destructuring declarations](destructuring-declarations.md):

0 commit comments

Comments
 (0)