在Kotlin中制作ParseObject的独立副本

时间:2018-11-02 13:42:22

标签: parse-platform kotlin

我在Kotlin ParseObject子类中实现了一个复制构造函数。

@ParseClassName("MySubclass")
class MySubclass: ParseObject {
    /** Registered ParseObject Subclasses require an empty primary constructor **/
    constructor()

    /** Copy Constructor **/
    constructor(original: MySubclass) : super() {
        myStrings = original.myStrings
        ...
    }

    var myStrings: MutableList<String>
        get() = getList("myStrings") ?: mutableListOf()
        set(value) = put("myStrings", value)

    ...

    /** 
     * Retrieves the list of Strings, then adds a new String to it before 
     * replacing the list in the ParseObject.
     **/
    fun addString(string: String) {
        val list = myStrings
        list.add(string)
        myStrings = list
    }
}

但是当我修改副本时,原件也会被修改。
为什么会这样呢?这种方法不应该产生两个不同的对象吗?

fun main(args : Array<String>) {

    val original = MySubclass()
    original.myStrings = listOf("This", "That")
    println("${original.myStrings.size}") // "2" as expected

    // Make a copy
    val newCopy = MySubclass(original)
    println("${newCopy.myStrings.size}") // "2" as expected

    // Modify the copy
    newCopy.addString("Other")
    println("${newCopy.myStrings.size}") // "3" as expected

    println("${original.myStrings.size}") // "3" why has this object been modified too???
}

0 个答案:

没有答案