2016-12-01 10 views
1

私はtranslationsと呼ばれるMutableMapを持っています。これを別のMutableMapまたはMapにクローンしたいです。私はこれを次のようにしています:translations.map { it.key to it.value }.toMap()MutableMapを複製する慣習的な方法は何ですか?

これは私にとっては「気分」ではありません。 MutableMapを複製するための慣用的な方法はありますか?

+2

Kotlin 1.0.5の質問に答えることはできませんが、1.1ではEST 1.1のように 'translations.toMutableMap()'になる可能性があります。 – hotkey

答えて

2

Kotlin 1.0.x標準ライブラリは、マップをコピーするための慣用方法を定義していません。 more慣用の方法はmap.toList().toMap()ですが、時にはのほとんどはです。コトルで何かを行う慣用方法は、自分で定義することです。です。例えば:

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()です。残念ながら、マップの性質は保持されません。つまり、結果のクラスは実装に依存します。

関連する問題