Kotlin 映射类型推断失败

Kotlin Map Type Inference Failed

我使用 Kotlin 中的两个可变字符串列表创建了一个映射:

val mapNames = mutableMapOf(Pair(initList, nameList))

当我尝试访问我尝试过的其中一个键的值时

print(mapNames.get("BB")) and print(mapNames["BB"]) 并抛出错误

error: type inference failed. The value of the type parameter K should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly.

两个列表都是字符串列表,我只是想简单地 return 与键关联的值。我试图将其类型明确指定为 String,但仍然抛出错误。我想知道我错过了什么?

您还没有创建 Map<String, String>。您已经创建了一个 Map<List<String>, List<String>>。映射中唯一的键是 initList,它对应于值 nameList。那显然不是你想要的。您希望 initList 中的每个事物都与 nameList 中的每个事物匹配并在地图中形成一个条目,以便您得到一个 Map<String, String>,对吧?

为此,您应该zip列表:

val mapNames = initList.zip(nameList).toMap(mutableMapOf())

zip 在这里创建一个 List<Pair<String, String>>,而 mutableMapOf 将把该列表中的每一对变成一个映射条目。然后就可以正常访问地图了。