Kotlin data class copy method not deep copying all members

旧时模样 提交于 2019-11-30 17:57:15

The copy method of Kotlin is not supposed to be a deep copy at all. As explained in the reference doc (https://kotlinlang.org/docs/reference/data-classes.html), for a class such as:

data class User(val name: String = "", val age: Int = 0)

the copy implementation would be:

fun copy(name: String = this.name, age: Int = this.age) = User(name, age)

So as you can see, it's a shallow copy. The implementations of copy in your specific cases would be:

fun copy(a: Int = this.a, bar: Bar = this.bar, list: MutableList<Int> = this.list) = Foo(a, bar, list)

fun copy(x: Int = this.x) = Bar(x)

As @Ekeko said, the default copy() function implemented for data class is a shallow copy which looks like this:

fun copy(a: Int = this.a, bar: Bar = this.bar, list: MutableList<Int> = this.list)

To perform a deep copy, you have to override the copy() function.

fun copy(a: Int = this.a, bar: Bar = this.bar.copy(), list: MutableList<Int> = this.list.toList()) = Foo(a, bar, list)

There is a way to make a deep copy of an object in Kotlin (and Java): serialize it to memory and then deserialize it back to a new object. This will only work if all the data contained in the object are either primitives or implement the Serializable interface

Here is an explanation with sample Kotlin code https://rosettacode.org/wiki/Deepcopy#Kotlin

Note: This solution should also be applicable in Android using the Parcelable interface instead of the Serializable. Parcelable is more efficient.

Building on a previous answer, an easy if somewhat inelegant solution is to use the kotlinx.serialization facility. Add the plugin to build.gradle as per the docs, then to make a deep copy of an object, annotate it with @Serializable and add a copy method which converts the object to a serialised binary form, then back again. The new object will not reference any objects in the original.

import kotlinx.serialization.Serializable
import kotlinx.serialization.cbor.Cbor

@Serializable
data class DataClass(val yourData: Whatever, val yourList: List<Stuff>) {

    var moreStuff: Map<String, String> = mapOf()

    fun copy(): DataClass {
        return Cbor.load(serializer(), Cbor.dump(serializer(), this))
    }

This won't be as fast as a handwritten copy function, but it does not require updating if the object is changed, so is more robust.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!