什么是克隆MutableMap的惯用方法?

我有一个名为translations的MutableMap。 我想将其克隆到另一个MutableMap或Map中。 我已经完成了以下内容: translations.map { it.key to it.value }.toMap()

这对我来说并不“感觉”。 有一个更习惯的方法来克隆一个MutableMap?

Kotlin 1.0.x标准库没有定义复制地图的惯用方式。 一个习惯的方式是map.toList().toMap()但是有时在Kotlin中习惯的方式是简单地定义你自己的扩展 。 例如:

 fun <K, V> Map<K, V>.toMap(): Map<K, V> = when (size) { 0 -> emptyMap() 1 -> with(entries.iterator().next()) { Collections.singletonMap(key, value) } else -> toMutableMap() } fun <K, V> Map<K, V>.toMutableMap(): MutableMap<K, V> = LinkedHashMap(this) 

上述扩展功能与版本1.1-M03(EAP-3)中定义的功能非常相似。

来自v1.1-M03的kotlin / Maps.kt·JetBrains / kotlin :

 /** * Returns a new read-only map containing all key-value pairs from the original map. * * The returned map preserves the entry iteration order of the original map. */ @SinceKotlin("1.1") public fun <K, V> Map<out K, V>.toMap(): Map<K, V> = when (size) { 0 -> emptyMap() 1 -> toSingletonMap() else -> toMutableMap() } /** * Returns a new mutable map containing all key-value pairs from the original map. * * The returned map preserves the entry iteration order of the original map. */ @SinceKotlin("1.1") public fun <K, V> Map<out K, V>.toMutableMap(): MutableMap<K, V> = LinkedHashMap(this) 

预期的方式是translations.toMutableMap() 。 不幸的是,它不保留地图的性质,这意味着所得到的类将取决于实现。