Search code examples
kotlinmutablemap

Why is the sum of two mutable maps in kotlin a map


I have two functions that return mutable maps

fun mumapone() = mutableMapOf<String, Any>("one" to 1)
fun mumaptwo() = mutableMapOf<String, Any>("two" to 1) + mumapone()

the type of fun mumaptwo() becomes a Map and not a MutableMap, why? It seems that the sum of two mutable maps will always be a Map, why is that?

I can also use variables but the output will be the same

    fun fakeConfig() = xx +  yy
    val xx = mutableMapOf<String, Any>("one", 1)
    val yy = mutableMapOf<String, Any>("two", 1)

the type of fakeConfig() will still be Map, the only way to change this is to cast it or

    (xx +  yy).toMutatleMap()

so to repeat the question why is the sum of two mutable maps becomes a map and not a mutable map.

cheers,

es


Solution

  • When you sum the two maps the interface that is assumed by default is Map, since MutableMap is an implementation of the interface it cannot be assumed for the + operator.

    However if you want to avoid casting or conversion you can simply create a third mutable map and sum the two other maps in it. That map will keep the type and will not need casting.

    More information in the kotlin docs: https://kotlinlang.org/docs/reference/map-operations.html#map-write-operations