如果密钥不存在,添加或更新映射密钥的最佳做法是什么

时间:2017-09-07 09:46:47

标签: scala

我想知道如果密钥不存在,添加或更新地图密钥的最佳做法是什么。 例如,这段代码将抛出异常。

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

由于

2 个答案:

答案 0 :(得分:2)

要更新条目是否缺席,您可以执行以下操作:

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

这是一个如何运作的例子

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

答案 1 :(得分:0)

这应该可以解决问题:

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")
}