Reputation: 2450
What is difference between plus() and put() methods in kotlin map?
I have created the map and use plus() method to add my key value pair but when I print the map, I can't find the added values. And then I have moved to put(). What is the behaviour of plus() method?
Upvotes: 6
Views: 9166
Reputation: 128
A regular Map
(which is immutable) can only be modified using the plus
function (that can also be invoked with the + operator).
The plus
operator works with pairs of values, and, by nature, does not modify the original map; it returns a new map with the new entry.
// mapA and mapB are different maps
val mapA = mapOf("a" to 1, "b" to 2)
val mapB = mapA + ("c" to 3)
When using a MutableMap
, in addition to plus
(which will still return a new map), there are a few more options to change a map's content: put
, set
(which is the [] operator) and plusAssign
(which is the += operator).
The difference between set
and put
, as function calls, is that put
returns the previous value of the key (or null), whereas set
does not return anything. Also, when using bracket syntax, you can't use it as a expression body for a function. It's specially useful when creating wrapper classes to access the data inside a map:
class SomeWrapper(private val backingMap: MutableMap<String, String?>) {
var someIntValue: Int?
get() = backingMap["someInt"]?.toIntOrNull()
set(value) = backingMap.set("someInt", value.toString())
// this is invalid because assignments are not expressions
// set(value) = backingMap["someInt"] = value
// this is also invalid because put would return String? instead of Unit
// set(value) = backingMap.put("someInt", value)
}
(of course, in the example above you could just change the setter to use block syntax instead of expression syntax, it's a matter of taste)
The syntax of plusAssign
is similar to plus
, but it will change the original map instead:
val map = mutableMapOf("a" to 1, "b" to 2)
map += ("c" to 3)
Upvotes: 6
Reputation: 97258
As described in the documentation, the plus
method (which is normally used in its operator form, +
) returns a new map containing the elements from the original map and the key/value pair passed to it as a parameter. It does not modify the map on which it was called.
The idiomatic way to add values to a Kotlin map is not to use the put
method, but to use square brackets:
map[key] = value
Upvotes: 11