如何在不将这些更改反映到原始对象的情况下复制伴生对象并进行更改?

How to copy companion object and make changes without reflecting these changes to the original object?

我正在使用伴随对象临时保存一些数据。

我可能想要更改此数据,而且我还想确保在进行更改时原始对象没有被更改。

我试过了。

companion object{
        var position: Int = 0
    } 
var copyPosition = positon
copyPosition--
println(copyPosition)

这工作得很好并打印 -1。原来的position没变。 (值 0 未更改。)

但是,与List<MyObject>相同的操作不起作用。

companion object{
        var list: MutableList<MyObject> = "...here objects are aquired..."
    } 
var tempList: MutableList<MyObject> = list
tempList.removeAt(0)
println(list.size)

在这里,如果我从 tempList 中删除项目,原始列表也会丢失该项目。我怎么能阻止这个?怎么能只对tempList进行修改而不对原来的list进行修改呢?

您正在向 tempList 提供 Companion object 列表的引用。所做的任何更改也会反映在列表中。你可以做的是创建一个新的 MutableList<MyOjbect).addAll() list 的所有对象到你的新 MutableList 对象

例子

val firstList = mutableListOf(1,2,3,4,5)  //0x543DE (Dummy memory address)

val secondList = firstList  //Giving reference of firstList to the secondList  //0x543DE

如您所见,secondList = firstList,我们将 firstList 引用给 secondList。可以这样想,您的 firstList val 持有对原始列表对象的引用。当我们写 secondList = firstList 时,我们给 secondList 提供了 firstList val 指向的列表的引用。现在这两个 val 都指向内存中的同一个对象。

现在 secondList 中所做的更改也会反映到 'original' 列表中。但为什么?你猜对了,因为它们都指向同一个对象。

至于解决方案,您可以:

companion object{
    var list: MutableList<MyObject> = "...here objects are aquired..."
} 
var tempList: MutableList<MyObject> = mutableListOf()
tempList.addAll(list) //This will iteratively copy list items to tempList
tempList.removeAt(0)
println(list.size)