Kotlin data class copy method not deep copying all members

前端 未结 5 1616
陌清茗
陌清茗 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:31

    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 = this.list) = Foo(a, bar, list)
    
    fun copy(x: Int = this.x) = Bar(x)
    

提交回复
热议问题