gpt4 book ai didi

从 Map::getOrElse 返回的 Kotlin mutableList() 不公开 add()

转载 作者:行者123 更新时间:2023-12-02 12:34:15 24 4
gpt4 key购买 nike

我有

data class Person(var name: String, var hobbies: List<String>)

val people = mutableListOf(
Person("joe", asList("biking", "baking")),
Person("jane", asList("baking")),
Person("jack", asList("painting"))
)
val map = mutableMapOf<String, List<String>>()

for ((name, hobbies) in people) {

for (hobby in hobbies) {

var peopleWithThisHobby = map.getOrElse(hobby, { mutableListOf() })
peopleWithThisHobby.plus(name)
map[hobby] = peopleWithThisHobby
}
}

println(map)

peopleWithThisHobby.plus(name) 行,IntelliJ 自动完成没有给我 add() 方法。

我必须改用:

var peopleWithThisHobby = map.getOrElse(hobby, { mutableListOf() })
peopleWithThisHobby = peopleWithThisHobby.plus(name)
map[hobby] = peopleWithThisHobby

什么给了?这是设计使然吗?从 getOrElse 调用中返回的 mutableList() 发生了什么?

我使用的是 Kotlin 插件版本:1.1.3-eap-85-IJ2017.2-1

最佳答案

那是因为你的 map 定义有一个 List 而不是 MutableList 作为值。将其更改为 MutableList 即可。

val map = mutableMapOf<String, List<String>>()

将上面的改成:

val map = mutableMapOf<String, MutableList<String>>()

关于从 Map::getOrElse 返回的 Kotlin mutableList() 不公开 add(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44836968/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com