There are 5 variations for the syntax of Map.plus() extension function. They are:
operator fun <K, V> Map<out K, V>.plus( pair: Pair<K, V> ): Map<K, V>
This extension function creates a new read-only map by replacing or adding an entry to this map from a given key-value pair.
operator fun <K, V> Map<out K, V>.plus( pairs: Iterable<Pair<K, V>> ): Map<K, V>
This extension function creates a new read-only map by replacing or adding entries to this map from a given collection of key-value pairs.
operator fun <K, V> Map<out K, V>.plus( pairs: Array<out Pair<K, V>> ): Map<K, V>
This extension function creates a new read-only map by replacing or adding entries to this map from a given array of key-value pairs.
operator fun <K, V> Map<out K, V>.plus( pairs: Sequence<Pair<K, V>> ): Map<K, V>
This extension function creates a new read-only map by replacing or adding entries to this map from a given sequence of key-value pairs.
operator fun <K, V> Map<out K, V>.plus( map: Map<out K, V> ): Map<K, V>
This extension function creates a new read-only map by replacing or adding entries to this map from another map.
In this example,
map1
containing key-value pairs 1 to 'a'
and 2 to 'b'
.3 to 'c'
.plus()
operator to add the new pair to map1
.fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b');
val pair = 3 to 'c';
val result = map1.plus(pair);
print(result);
}
{1=a, 2=b, 3=c}
In this example,
map2
containing key-value pairs 'a' to 1
and 'b' to 2
.('c' to 3)
and ('d' to 4)
.plus()
operator to add the list of pairs to map2
.fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2);
val pairs = listOf('c' to 3, 'd' to 4);
val result = map2.plus(pairs);
print(result);
}
{a=1, b=2, c=3, d=4}
In this example,
map3
containing key-value pairs 1 to "apple"
and 2 to "banana"
.(3 to "cherry")
and (4 to "date")
.plus()
operator to add the array of pairs to map3
.fun main(args: Array<String>) {
val map3 = mapOf(1 to "apple", 2 to "banana");
val array = arrayOf(3 to "cherry", 4 to "date");
val result = map3.plus(array);
print(result);
}
{1=apple, 2=banana, 3=cherry, 4=date}
In this Kotlin tutorial, we learned about plus() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.