Saturday 18 January 2020

Kotlin: Immutable Map.update

Kotlin comes with immutable collection interfaces, including map, list, set, etc...

Now with the immutable maps I often need to change just one value in the map and do calculations on that modified map. I do not simply need to set a new value, but rather calculate a new value from the old one. A good example could be adding a number to the stored value.

Let's see how it looks like in java, because everyone understands java.


 


Now as usual with java, this is anything but easy to read, but I hope you get the point. Kotlin can do a bit better by using the operators feature.



I hope it looks a bit better, but I did not find it expressive enough, and I have to do this a lot, hundreds of places in the source code. So I wrote an extension function for the Map type called update. This is how it looks



Initially the implementation of this Map.update was indeed simply based on the + (plus) operator function. However, I have noticed that there is a faster way to perform this operation, it is faster to map all the key-value pairs and replace the single value. The benchmark result shows significantly better performance:





To sum up, I think this is the relatively rare ideal case when a more human-readable, more expressive code is also better performing.