【发布时间】:2022-12-17 10:19:26
【问题描述】:
更新不可变列表中特定项目的最佳方法是什么。例如,我有Item 的列表。我有几种更新列表的方法:
1.
fun List<Item>.getList(newItem: Item): List<Item> {
val items = this.toMutableList()
val index = items.indexOf(newItem)
if (index != -1) {
items[index ] = newItem
}
return items
}
fun List<Item>.getList(newItem: Card): List<Item> {
return this.map { item ->
if (item.id == newItem.id) newItem else item
}
}
第二个选项看起来更简洁,我更喜欢它。但是,在第二个选项中,我们将遍历列表中的每个元素,这对我来说很不利,因为列表可以包含很多元素。
请问,有没有更好的方法来满足我的要求?
【问题讨论】:
标签: kotlin arraylist collections kotlin-extension