Search code examples
scalacollections

Put if absent to map in scala


I have the following map:

val m: mutable.Map[String, Long] = mutable.Map()

and I want to just put some value into it if it's not present. If it is present in turn I want to perform some computations:

Currently I do it in the following way:

val key: String = //...
val value: Long = //...
m(key) = m.getOrElse(key, 0L) + value

But this feels a bit verbose to me (In Java we have putIfAbsent method). Is there a shorter way to do so in Scala?


Solution

  • For mutable maps you can either override the default method, or add a default computation with withDefault, so that it automatically computes all the missing values on first access:

    val m = new HashMap[String, Int].withDefault(k => 0)
    

    Then you can update the values like this:

    m("foo") += 5
    m("bar") += 7
    m("foo") += 37
    
    println(m) // Map(foo -> 42, bar -> 7)
    

    Or just use getOrElseUpdate:

    val m = collection.mutable.HashMap.empty[String, Long]
    val k = "the key"
    
    m(k) = m.getOrElseUpdate(k, 0L) + 1