Kotlin data class copy method not deep copying all members

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

    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

    import java.io.Serializable
    import java.io.ByteArrayOutputStream
    import java.io.ByteArrayInputStream
    import java.io.ObjectOutputStream
    import java.io.ObjectInputStream
    
    fun  deepCopy(obj: T?): T? {
        if (obj == null) return null
        val baos = ByteArrayOutputStream()
        val oos  = ObjectOutputStream(baos)
        oos.writeObject(obj)
        oos.close()
        val bais = ByteArrayInputStream(baos.toByteArray())
        val ois  = ObjectInputStream(bais)
        @Suppress("unchecked_cast")
        return ois.readObject() as T
    } 
    

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

提交回复
热议问题