The syntax of Map.toMutableMap() extension function is:
fun <K, V> Map<out K, V>.toMutableMap(): MutableMap<K, V>
This toMutableMap() extension function of Map returns a new mutable map containing all key-value pairs from the original map.
In this example,
map1
containing integer keys and character values.toMutableMap()
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.toMutableMap()
println(result)
}
{1=a, 2=b, 3=c}
In this example,
map2
containing character keys and integer values.toMutableMap()
function on map2
.map2
is returned.fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val result = map2.toMutableMap()
println(result)
}
{a=1, b=2, c=3}
In this example,
map3
containing string keys and integer values.toMutableMap()
function on map3
.map3
is returned.fun main(args: Array<String>) {
val map3 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val result = map3.toMutableMap()
println(result)
}
{apple=1, banana=2, cherry=3}
In this Kotlin tutorial, we learned about toMutableMap() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.