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不应该被改变,这样做是危险的.

Kotlin相关问答推荐

如果一项工作失败,请继续在Kotlin 等待其他工作/子元素完成

Spring Boot Bean验证器未触发

如何为集成测试配置Gradle JVM测试套件?

jOOQ Kotlin Coroutines - Select all and exists查询

Kotlin stlib中是否有用于将列表<;对<;A,B&>;转换为对<;列表<;A&>,列表<;B&>;的函数

kotlin - 挂起简单方法调用链时可能存在冗余分支

Kotlin 基于参数类型的返回类型推断

Ktor 在 Heroku 上的 CORS 问题,但在本地没有

Kotlin SIZE_BYTES

Kotlin Path.useLines { } - 如何不获取 IOException("Stream closed")?

将 SharedPreferences 中的值公开为流

在 Kotlin 中,::class.simpleName是做什么的?

无法为 retrofit2.Call 调用无参数构造函数

更新到版本4.10.1/4.10.2后 Gradle 同步失败

TornadoFX 中设置 PrimaryStage 或 Scene 属性的方法

如何获取Kotlin中变量的名称?

如何在 Gradle Kotlin DSL 中使用来自 gradle.properties 的插件版本?

在 Android 12 (SDK 31) 中获取 android.app.ForegroundServiceStartNotAllowedException

var str:String是可变的还是不可变的?

Android Compose 生产准备好了吗?