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

时间:2017-06-30 00:38:45

标签: kotlin

我有

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

是什么给出的?这是设计的吗?在mutableList()来电中返回的getOrElse会发生什么?

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

1 个答案:

答案 0 :(得分:6)

这是因为您的地图定义的值为List而不是MutableList。将其更改为MutableList,它就能正常运作。

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

将上述内容更改为:

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