There are 2 variations for the syntax of Map.toMap() extension function. They are:
fun <K, V> Map<out K, V>.toMap(): Map<K, V>
This extension function returns a new read-only map containing all key-value pairs from the original map.
fun <K, V, M : MutableMap<in K, in V>> Map<out K, V>.toMap( destination: M ): M
This extension function populates and returns the destination mutable map with key-value pairs from the given map.
In this example,
map1
containing integer keys and character values.toMap()
function on map1
.map1
is returned.fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val result = map1.toMap()
println(result)
}
{1=a, 2=b, 3=c}
In this example,
map2
containing character keys and integer values.mutableMap
.toMap()
function on map2
, populating the mutableMap
with key-value pairs from map2
.mutableMap
is returned with the key-value pairs from map2
.fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val mutableMap = mutableMapOf<Char, Int>()
val result = map2.toMap(mutableMap)
println(result)
}
{a=1, b=2, c=3}
In this example,
map3
containing integer keys and character values.mutableMap
with different key and value types.toMap()
function on map3
, populating the mutableMap
with key-value pairs from map3
.mutableMap
is returned with the key-value pairs from map3
.fun main(args: Array<String>) {
val map3 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val mutableMap = mutableMapOf<Int, Char>()
val result = map3.toMap(mutableMap)
println(result)
}
{1=a, 2=b, 3=c}
In this Kotlin tutorial, we learned about toMap() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.