gpt4 book ai didi

kotlin - Kotlin:从对列表而不是varargs创建可变映射?

转载 作者:行者123 更新时间:2023-12-02 13:07:42 25 4
gpt4 key购买 nike

我在 Kotlin 有一个 list 。我需要从列表的每个元素创建一个映射到一个空的可变集合,就像这样-

var mutableMap: MutableMap<Int, MutableSet<Int>> = mutableMapOf(someList.map{ it to mutableSetOf<Int>() })

但我收到此错误-
Type mismatch.
Required:
Pair<TypeVariable(K), TypeVariable(V)>
Found:
List<Pair<Int, MutableSet<Int>>>

我知道mutableMapOf()接受 varargs pairs,所以我尝试了传播运算符( *),但这也没有用。请帮我达到目的。

最佳答案

散布运算符适用于数组,而不适用于列表。同样,如果将变量类型定义为集合映射而不是MutableSet的MutableMap,则将其强制转换为不可变。因此,要修复您的代码:

var mutableMap: MutableMap<Int, MutableSet<Int>> = mutableMapOf(*someList.map{ it to mutableSetOf<Int>() }.toTypedArray())

但是这样做会更清洁:
val map = someList.associateWith { mutableSetOf<Int>() }.toMutableMap()

关于kotlin - Kotlin:从对列表而不是varargs创建可变映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60953016/

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