Kotlin data class copy method not deep copying all members

前端 未结 5 1623
陌清茗
陌清茗 2020-12-15 04:03

Could someone explain how exactly the copy method for Kotlin data classes work? It seems like for some members, a (deep) copy is not actually created and the re

5条回答
  •  星月不相逢
    2020-12-15 04:29

    Beware of those answers who are just copying list reference from an old object into the new one. Only quick way of deep copying I have found is to either serialize/deserialize objects i.e. convert the objects into JSON and then transform them back to POJO. If you are using GSON, here is the piece of code:

    class Foo {
        fun deepCopy() : Foo {
            return Gson().fromJson(Gson().toJson(this), this.javaClass)
        }
    }
    

提交回复
热议问题