【发布时间】:2021-10-25 10:59:09
【问题描述】:
来自here
下面为测试用例提供
@Test
fun testKotlinArrayCopy() {
data class Person(val name: String, var friends: List<Person>, var isHungry: Boolean = false)
val okyFriends = listOf(
Person(name = "Billy", friends = listOf()),
)
val peopleAtBlock1 : ArrayList<Person> = arrayListOf(
Person(name = "Oky", friends = okyFriends),
)
val peopleAtBlock2 : ArrayList<Person> = ArrayList(peopleAtBlock1.toMutableList())
peopleAtBlock1[0].friends[0].isHungry = true
// here i expect variable peopleAtBlock2 doesn't changed
// because i just change the peopleAtBlock1 only
assertFalse(peopleAtBlock1[0] == peopleAtBlock2[0])
}
当我运行测试时,它失败了,因为 peopleAtBlock2 由此代码导致意外更改
peopleAtBlock1[0].friends[0].isHungry = true
我想保持peopleAtBlock2 的值不变,我该怎么做?
谢谢
编辑:
我已经关注答案here 使用
fun Array<BooleanArray>.copy() = map { it.clone() }.toTypedArray()
转换为我的情况,函数将是
fun ArrayList<Person>.copy2() = map { it.copy() }.toTypedArray()
还是不行
如果您没有 kotlin,请检查 my repl 是否在云中运行
【问题讨论】:
-
我明白了,谢谢,等等
-
重复:stackoverflow.com/questions/40463390/… 没有足够的代表发表评论,抱歉
-
等一下让我试试代码
-
@ShobhitTewari 它不起作用,请查看我编辑的帖子
标签: list kotlin arraylist copy