If I have an immutableMap: Map<String, Int>
and want to convert it to a mutableMap: MutableMap<String, Int>
, what would be the best way to do that? There doesn't seem like any convenient way.
If I have an immutableMap: Map<String, Int>
and want to convert it to a mutableMap: MutableMap<String, Int>
, what would be the best way to do that? There doesn't seem like any convenient way.
Update: The Kotlin 1.1 stdlib has a .toMutableMap()
function. This should be used instead of creating your own.
----------------------- Old Answer Below ------------------------------
下面的扩展函数通过将Map
复制到MutableMap
来工作.
fun <K, V> Map<K, V>.toMutableMap(): MutableMap<K, V> {
return HashMap(this)
}
其他一些答案建议判断 map 是否为MutableMap
,然后再 Select 是否为MutableMap
.这应该不惜一切代价避免,因为这是一种不好的做法.事实上,在Kotlin ,它被降到了Map
,这意味着这个Map
不应该被改变,这样做是危险的.