'Initialising map with an existing map in kotlin

I start with one map myInitialMap. i would like to create another map myNewMap that is initialised with myInitialMap.

val myInitialMap = mapOf<String, Int>("one" to 1, "two" to 2)
val myNewMap = mapOf(myInitialMap)

I get error:

Type mismatch.
Required: Pair<TypeVariable(K), TypeVariable(V)>
Found: Map<String, Int>

How can I initialise myNewMap with myInitialMap?



Solution 1:[1]

You can use myInitialMap.toList().toMutableStateMap().

The ...Of() functions in Kotlin all follow the convention of taking individual entries as varargs, which is why mapOf(myInitialMap) doesn't, and shouldn't, work. Since these functions use the arguments to determine the generic types, the list/set versions could not possibly support also having overloads that accept an Iterable parameter with all the entries to include, because you might actually want a list of Iterables (2D collection). For consistency, mapOf must behave the same.

Function naming/behavior conventions:

  • ...Of(): A function taking a vararg parameter of all the individual values to put in the collection. The argument type can be used for the compiler to infer the generic type(s) of the collection.
  • .to...Map/Set/List(): An extension function that creates a shallow copy or new type of collection from the entries of the collection it is called on.
  • .as...(): An extension function that wraps the original object in another one. For example, asIterable() or asSequence() will return those types, but they will read from the original object. They are not copies.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tenfour04