St.Antario
St.Antario

Reputation: 27385

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?

Upvotes: 5

Views: 6398

Answers (2)

Andrey Tyukin
Andrey Tyukin

Reputation: 44918

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

Upvotes: 7

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

You're looking for mutable.Map.getOrElseUpdate:

m.getOrElseUpdate(key, value)

Upvotes: 8

Related Questions