In Kotlin, the plus method creates a new read-only Map from the current LinkedHash by adding or replacing the map entries that are passed as an argument to it.
operator fun <K, V> Map<out K, V>.plus(
map: Map<out K, V>
): Map<K, V>
This method takes a Map as an argument.
If the passed map contains an entry with the key already present in the LinkedHashMap, the entry’s value of the LinkedHashMap will be replaced by the value of the Map argument.
If the passed map contains an entry that is not present in the LinkedHashMap, then a new entry will be added to the LinkedHashMap.
This method returns a read-only Map by combining the current LinkedHashMap with the Map that is passed as an argument to it.
The code given below demonstrates how we can use the plus method:
fun main() {//create a new LinkedHashMap which can have integer type as key, and string type as valueval map: LinkedHashMap<Int, String> = linkedMapOf()// add two entriesmap.put(1, "one")map.put(2, "two")map.put(3, "three")println("\nThe map is : $map")val argumentMap = mapOf(1 to "ONE", 4 to "FOUR")println("The argumentMap is : $argumentMap")var newMap = map.plus(argumentMap);println("\nmap.plus(argumentMap) : ${newMap}")}
Line 3: We create a new LinkedHashMap object with map. We use the linkedMapOf method to create an empty LinkedHashMap.
Lines 6–8: We add three entries to the map {1=one,2=two,3=three}, using the put method.
Line 12: We create another map with the name argumentMap, using the mapOf method. This map has two entries {1=ONE,4=FOUR}.
Line 15: We use the plus method with argumentMap as an argument. This method creates a new map by combining the entries of the map with argumentMap. In our case:
1=one of the map will be replaced by the entry 1=ONE of the argumentMap.4=FOUR of the argumentMap will be added to the map object.The read-only map that is returned will be {1=ONE, 2=two, 3=three, 4=FOUR}.