Joseph McDermott
Joseph McDermott

Reputation: 412

Duplicate a nested Map to a MutableMap in Kotlin

Given a nested immutable map of:

val someNestedMap = mapOf(
    2 to mapOf(
        "a" to true,
        "b" to false,
        "c" to true
    ),
    3 to mapOf(
        "d" to false,
        "e" to true,
        "f" to false
    )
)

If I want a new copy of this exact structure, but with each of the maps to be mutable, is there an easy way to do this in Kotlin?

I want to create a copy of the above as val newCopy: MutableMap<Int, MutableMap<Int, Boolean>>

Upvotes: 0

Views: 1281

Answers (2)

Tenfour04
Tenfour04

Reputation: 93581

You can one-line this by mapping the keys and then converting the whole map:

return immutableMap.mapValues { it.value.toMutableMap() }.toMutableMap()

You could make a generic extension function out of it like this:

fun <K, VK, VV> Map<K, Map<VK, VV>>.toDeeplyMutableMap() = 
    mapValues { it.value.toMutableMap() }.toMutableMap()

I think this is too specific of a use case for a standard library function. Nested mutable collections are kind of error prone.

Upvotes: 2

Joseph McDermott
Joseph McDermott

Reputation: 412

Once again, I came up with something soon after posting. Not sure if it's the best approach though, feels like there should be a native function for this:

fun copyIt(immutableMap: Map<Int, Map<Int, Boolean>>): MutableMap<Int, MutableMap<Int, Boolean>>
{
    val newCopy: MutableMap<Int, MutableMap<Int, Boolean>> = mutableMapOf()

    for (mapValue in immutableMap.entries) {
        newCopy[mapValue.key] = mapValue.value.toMutableMap()
    }

    return newCopy
}

Upvotes: 0

Related Questions