Scala HashMap getOrElse 与 getOrElseUpdate

使用Map的过程中,发现有和 getOrElse 相似的方法 getOrElseUpdate ,大概看下具体是在做什么~


getOrElse

getOrElse经常用到,当 HashMap 获取某个不存在的key时会返回一个default默认值,从而避免出现 null point 的情况

/** Returns the value from this `Success` or the given `default` argument if this is a `Failure`.
 *
 * ''Note:'': This will throw an exception if it is not a success and default throws an exception.
 */
def getOrElse[U >: T](default: => U): U =
  if (isSuccess) get else default

getOrElseUpdate

getOrElseUpdate 其实是 getOrElse的升级版,当获取不存在的key时,不再返回默认值 default,而是根据 op 这个方法根据当前获取的不存在的key返回一个value,并将这个 key-value 存入 HashMap,这也就是 update 的由来

/** If given key is already in this map, returns associated value.
 *
 *  Otherwise, computes value from given expression `op`, stores with key
 *  in map and returns that value.
 *
 *  Concurrent map implementations may evaluate the expression `op`
 *  multiple times, or may evaluate `op` without inserting the result.
 *  
 *  @param  key the key to test
 *  @param  op  the computation yielding the value to associate with `key`, if
 *              `key` is previously unbound.
 *  @return     the value associated with key (either previously or as a result
 *              of executing the method).
 */
def getOrElseUpdate(key: A, op: => B): B =
  get(key) match {
     
    case Some(v) => v
    case None => val d = op; this(key) = d; d
  }

Test ⤵️

val testHashMap = mutable.HashMap[String,Int]()

# 定义 update 规则
def op(num: String) :Int = Try(num.toInt).getOrElse(0) * 2
def update(s: String): Int = testHashMap.getOrElseUpdate(num,op(num))

# key "1" 存在 key "2" 不存在 
testHashMap("1") = 1
val value_1 = update("1")
val value_2 = update("2")
    
# 检查执行结果
println(value_1,value_1)
println(testHashMap)
(1,4)
Map(2 -> 4, 1 -> 1)

你可能感兴趣的:(Scala,常用语法,scala,getOrElse,getOrElseUpdate)