Last active
May 14, 2018 11:45
-
-
Save enshahar/125ef1a3e93ebb77ec564c96e26a8ce5 to your computer and use it in GitHub Desktop.
Is Kotlin's data class copy() deep?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data class SubData(var x:Int, var y:String) | |
data class Data(val d:SubData, val i:Int) | |
val x = Data(SubData(10, "shared data"), 10) | |
val z = x.copy() | |
println("x.d.x = ${x.d.x}, x.d.y = ${x.d.y}") | |
println("z.d.x = ${z.d.x}, z.d.y = ${z.d.y}") | |
x.d.x = 100 | |
println("after chaning x.d.x to 100") | |
println("x.d.x = ${x.d.x}, x.d.y = ${x.d.y}") | |
println("z.d.x = ${z.d.x}, z.d.y = ${z.d.y}") | |
val z2 = x.copy(d = SubData(100,"new data")) | |
x.d.x = 200 | |
println("after setting d a new SubData and chaning x.d.x to 200") | |
println("x.d.x = ${x.d.x}, x.d.y = ${x.d.y}") | |
println("z.d.x = ${z.d.x}, z.d.y = ${z.d.y}") | |
println("z2.d.x = ${z2.d.x}, z2.d.y = ${z2.d.y}") | |
// $ kotlinc -script DataCopy.kts | |
// x.d.x = 10, x.d.y = shared data | |
// z.d.x = 10, z.d.y = shared data | |
// after chaning x.d.x to 100 | |
// x.d.x = 100, x.d.y = shared data | |
// z.d.x = 100, z.d.y = shared data | |
// after setting d a new SubData and chaning x.d.x to 200 | |
// x.d.x = 200, x.d.y = shared data | |
// z.d.x = 200, z.d.y = shared data | |
// z2.d.x = 100, z2.d.y = new data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
so the key point here is "scala and kotlin uses the immutablilty to provide the deep-copying in their copy(), actually that is the sharing of same sub-object-graph"