kevinjoeiy
kevinjoeiy

Reputation: 121

what best practice to add or update map key if key doesn't exists

I wonder what is the best practice to add or update map key if key doesn't exists. For instance this piece of code will throws exception.

val states = scala.collection.mutable.Map[Int, String]()
states(1) = "Alaska"
states(2) = states(2) + " A Really Big State" // throws null pointer exeption

Thanks

Upvotes: 1

Views: 2264

Answers (2)

Simon
Simon

Reputation: 6363

To update if the entry is absent you can do:

states.getOrElseUpdate(2, " A Really Big State")

Here's an example of how it works

val states = scala.collection.mutable.Map[Int, String]()
val empty = states.get(2) // empty == None
val bigState = states.getOrElseUpdate(2, "A Really Big State") // bigState == A Really Big State
val stillBigState = states.getOrElseUpdate(2, "An even bigger state") // stillBigState == A Really Big State

Upvotes: 5

Sohum Sachdev
Sohum Sachdev

Reputation: 1397

This should do the trick:

val states = scala.collection.mutable.Map[Int, String]()
states(1) = "Alaska"
states.get(2) match {
  case Some(e) => states.update(2, e + "A really Big State")
  case None => states.put(2, "A really Big State")
}

Upvotes: 2

Related Questions