Is there an elegant way in to update an already existing value in a Map?
This looks too scary:
val a = map.get ( something )
if ( a != null ) // case .. excuse my old language
a.apply( updateFunction )
else
map.put ( something, default )
Most of the time you can insert something that can be updated when it's created (e.g. if it's a count, you put 0 in it and then update to 1 instead of just putting 1 in to start). In that case,
map.getOrElseUpdate(something, default).apply(updateFunction)
In the rare cases where you can't organize things this way,
map(something) = map.get(something).map(updateFunction).getOrElse(default)
(but you have to refer to something
twice).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With