Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic way to clone a MutableMap?

Tags:

kotlin

I have a MutableMap called translations. I want to clone this, into another MutableMap or a Map. I have done this with the following: translations.map { it.key to it.value }.toMap()

This doesn't 'feel' right to me. Is there a more idiomatic way to clone a MutableMap?

like image 863
Arthur Avatar asked Dec 14 '25 18:12

Arthur


1 Answers

In Kotlin 1.1+ you can use toMutableMap:

val mutableMap = mutableMapOf("a" to 1, "b" to 2)
val mutableMapCopy = mutableMap.toMutableMap()
mutableMap.clear()
println(mutableMap) //=> {}
println(mutableMapCopy) //=> {a=1, b=2}

Kotlin Playground: https://pl.kotl.in/LGhPpdjv5


The Kotlin 1.0.x Standard Library does not define an idiomatic way to copy a map. A more idiomatic way would be map.toList().toMap() but sometimes the most idiomatic way to do something in Kotlin is to simply define your own extensions. e.g.:

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)

The above extension functions are very similar to what is defined in release 1.1-M03 (EAP-3).

From 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)
like image 181
mfulton26 Avatar answered Dec 18 '25 11:12

mfulton26



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!