2017-09-07 50 views
0

我不知道在密鑰不存在的情況下添加或更新地圖密鑰的最佳做法是什麼。 例如這段代碼會拋出異常。如果密鑰不存在,添加或更新地圖密鑰的最佳做法

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

感謝

+0

如果你有使用可變映射(你可能不需要),只需使用java的'ConcurrentHashMap' ...至少,它是線程安全的。它也有'putIfAbsent'和'computeIfAbsent' – Dima

回答

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

要更新,如果項不存在,你可以這樣做:

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