2016-12-01 30 views
1

我有一個名爲translations的MutableMap。我想將其克隆到另一個MutableMap或Map中。我做了以下幾點:translations.map { it.key to it.value }.toMap()什麼是克隆MutableMap的習慣用法?

這並不「感覺」對我。有沒有一種更習慣的方式來克隆MutableMap?

+2

不回答Kotlin 1.0.5的問題,但在1.1中它可能是'translations.toMutableMap()',就像現在在1.1 EAP中一樣。 – hotkey

回答

2

Kotlin 1.0.x標準庫沒有定義複製地圖的慣用方式。 A 更多慣用的方式將是map.toList().toMap()但有時大多數在Kotlin做某事的慣用方式是簡單地定義您自己的extensions。例如: -

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) 

以上擴展功能非常類似於在release 1.1-M03 (EAP-3)定義。

kotlin/Maps.kt at v1.1-M03 · 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) 
1

爲預期的方式是translations.toMutableMap()。不幸的是,它不保留地圖的性質,這意味着所得到的類將取決於實現。

相關問題