Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update present values in a mutable.Map?

Tags:

scala

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 )
like image 299
cybye Avatar asked Jan 25 '13 19:01

cybye


1 Answers

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).

like image 105
Rex Kerr Avatar answered Oct 27 '22 12:10

Rex Kerr