Skip to content

Commit 32ce570

Browse files
authored
feat(kotlin-collections): add list deep clone example and tests (#1181)
* feat(kotlin-collections): add list deep clone tests * remove extraneous import * update style and names * add assertions * add address `isNotSameAs` assertion * reorder assertions
1 parent 9898b39 commit 32ce570

File tree

1 file changed

+41
-0
lines changed
  • core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com/baeldung/lists

1 file changed

+41
-0
lines changed

Diff for: core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com/baeldung/lists/ListCopyUnitTest.kt

+41
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,45 @@ class ListCopyUnitTest {
1818
assertThat(copied).isNotSameAs(cities)
1919
assertThat(copied[0]).isSameAs(cities[0])
2020
}
21+
22+
@Test
23+
fun `should deep copy a data class with only primitive fields`() {
24+
data class Person(var name: String, var age: Int)
25+
val persons = listOf(Person("Bob", 20), Person("Alice", 21))
26+
val personsCopy = persons.map { it.copy() }
27+
28+
assertThat(personsCopy).isNotSameAs(persons)
29+
assertThat(personsCopy[0]).isNotSameAs(persons[0])
30+
assertThat(persons[0].age).isEqualTo(personsCopy[0].age)
31+
32+
personsCopy[0].age = 22
33+
34+
assertThat(persons[0].age).isNotEqualTo(personsCopy[0].age)
35+
}
36+
37+
@Test
38+
fun `should deep copy a data class using a custom clone method`() {
39+
data class Address(var streetName: String, var streetNumber: Int, var city: String)
40+
41+
data class Person(val name: String, val age: Int, val address: Address) {
42+
fun clone(): Person {
43+
return Person(this.name, this.age, this.address.copy())
44+
}
45+
}
46+
47+
val address1 = Address("Sesame Street", 1, "CartoonLand")
48+
val address2 = Address("Sesame Street", 2, "CartoonLand")
49+
val persons = listOf(Person("Bob", 20, address1), Person("Alice", 21, address2))
50+
51+
val personsCopy = persons.map { it.clone() }
52+
53+
assertThat(personsCopy).isNotSameAs(persons)
54+
assertThat(personsCopy[0]).isNotSameAs(persons[0])
55+
assertThat(personsCopy[0].address).isNotSameAs(persons[0].address)
56+
assertThat(personsCopy[0].address).isEqualTo(persons[0].address)
57+
58+
personsCopy[0].address.streetNumber = 10
59+
60+
assertThat(personsCopy[0].address).isNotEqualTo(persons[0].address)
61+
}
2162
}

0 commit comments

Comments
 (0)