我正在尝试编辑位于MutableList中的元素,但它们似乎是val类型。以下是我尝试过的方法:
for(note in item.notes.toMutableSet()) {
note = note.trim()
}我一直收到这样的错误: val不能被重新分配。关于如何直接从列表中编辑元素以及如何将此更改反映在列表中的任何建议。
发布于 2021-02-28 16:21:56
为什么不创建一个新的集合,就像这样?
val newNotes = item.notes.map{ it.trim() }.toSet()for表达式中的note变量是不可变的
发布于 2021-02-28 17:27:57
对于不可变元素的可变列表,您可以对就地突变执行以下操作:
val list = mutableListOf(" 111 ", " 123 ")
for ((index, value) in list.withIndex()) {
list[index] = value.trim()
}发布于 2021-02-28 17:35:10
如果对象已经有方法来改变它自己的状态,那么遍历它就足够了,因为您并没有修改集合本身
给定以下对象:
data class Thing(var thing: String) {
fun trimThing() {
thing = thing.trim()
}
}
// somewhere else
fun trimAll(things: List<Thing>) {
// No need to edit the list because the mutation happens on the item level
things.forEach { thing -> thing.trimThing() }
}但是,如果您想改变列表本身,则需要将列表(或任何集合)转换为MutableCollection。下面是一个包含列表的示例
Kotlin已经提供了专门为你做这件事的实用函数:
fun trimStrings(strs: List<String>): List<String> {
val mutStrs = strs.toMutableList()
for(i in 0 until mutStrs.size) {
mutStrs[i] = mutStrs[i].trim()
}
return mutStrs.toList()
}存在针对其他集合类型的对称调用,例如Set -> MutableSet
尽管这很好,但我们仍然在处理可变性,这在Kotlin中是不受欢迎的,因为它是导致bug的常见原因。
As @Twistleton建议使用更多的 kotlinish (惯用Kotlin)来创建一个新的列表,而不是使用
fun trimNotes(item: YourType) {
return item.notes.map{ it.trim() }
}https://stackoverflow.com/questions/66406897
复制相似问题