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

Viewed 541

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

5 Answers

In general + is for immutable operatons that return you a new data-structure.

You could implement the + operator for MutableMap, but that wouldn't be a good idea because the putAll() function already exists for that:

fun main() {
    val foo = mutableMapOf(1 to "one", 2 to "two")
    val bar = mapOf(3 to "three", 4 to "four")
    foo.putAll(bar)
    println(foo)
}

Output:

{1=one, 2=two, 3=three, 4=four}

It's best to use + to get a new immutable map, or explicitly use mutable operations such as putAll().

You could write mumaptwo like this:

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

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

From documentation:

plus

Creates a new read-only map by replacing or adding entries to this map from another map.

operator fun <K, V> Map<out K, V>.plus(
    map: Map<out K, V>
): Map<K, V>

Mutable maps offer map-specific write operations. These operations let you change the map content using key-based access to the values.

The MutableMap is nothing but a map having write operation

There are certain rules that define write operations on maps:

Values can be updated. In turn, keys never change: once you add an entry, its key is constant.

For each key, there is always a single value associated with it. You can add and remove whole entries.

ADD Operation

To add a new key-value pair to a mutable map, use put().

To add multiple entries at a time, use putAll()

You can also add new entries to maps using the shorthand operator form. There are two ways:

plusAssign (+=) operator.

the [] operator alias for set().

Related