英文:
Update all list element based on the function result
问题
以下是您要求的翻译部分:
有很多在互联网和stackoverflow上的示例。但据我所见,它是根据索引实现的。但我想要根据单个函数的结果来更新所有项目。
下面的示例是我的简化版本:
data class Person(val id: Int, val name: String)
var tempList: List<Pair<Person, Boolean?>> = emptyList()
val personList = listOf(Person(1, "1"), Person(2, "2"), Person(3, "3"))
fun processPerson(person: Person): Boolean {
return person.name == "1"
}
fun main() {
tempList = personList.map { item ->
Pair(item, null)
}
tempList.forEach { item ->
println(processPerson(item.first))
}
}
我希望这可以满足您的要求。
英文:
There are loads of examples on the internet and on stackoverflow. But as far as I can see it is implemented according to index. But I want all items to be updated based on a single function result.
Below example is my simpyfied version:
data class Person(val id: Int, val name: String)
var tempList: List<Pair<Person, Boolean?>> = emptyList()
val personList = listOf(Person(1, "1"), Person(2, "2"), Person(3, "3"))
fun processPerson(person: Person): Boolean {
return person.name == "1"
}
fun main() {
tempList = personList.map { item ->
Pair(item, null)
}
tempList.forEach { item ->
println(processPerson(item.first))
}
}
Expected updated version of my list is:
listOf(Pair(Person(1, "1"), true), Pair(Person(2, "2"), false), Pair(Person(3, "3"), false))
答案1
得分: 2
以下是您要翻译的内容:
您可以立即构建列表如下:
tempList = personList.map { item ->
Pair(item, processPerson(item))
}
如果您真的需要使用初始的 tempList
,那么您唯一能做的是:
tempList = tempList.map {
Pair(it.first, processPerson(it.first))
}
或者
tempList = tempList.map {
it.copy(second = processPerson(it.first))
}
由于原始的 Pair 值是不可变的,所以无法更新它们,唯一的选择是映射到新的 Pair。
英文:
You could have constructed the list right away with
tempList = personList.map { item ->
Pair(item, processPerson(item))
}
If you really need to work with the initial tempList
then all you can do is
tempList = tempList.map {
Pair(it.first, processPerson(it.first))
}
or
tempList = tempList.map {
it.copy(second = processPerson(it.first))
}
There's no way to update the original Pairs because their values are immutable so the only option is to map to new Pairs
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论