Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between plus() and put() methods in kotlin map?

Tags:

kotlin

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?

like image 879
esu Avatar asked Dec 13 '22 18:12

esu


1 Answers

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
like image 126
yole Avatar answered Dec 17 '22 23:12

yole