首页  

scala函数式与非函数式写法比较     所属分类 scala 浏览量 584
注意 
ConcurrentHashMap key 和 value 都不能为null 
这里一定要用 Integer 不能用 Int 
用Int ,不存在的key返回为 0 


val map = new java.util.concurrent.ConcurrentHashMap[String, Integer]()
map.put("a",1)
map.put("b",2)

// scala 式写法
def printAndRemove(key:String):Unit = {
  Option(key).foreach{ k =>
    Option(map.get(k)).foreach{value =>
      println("value="+value)
      map.remove(k)
    }
  }
}

// 尽早return ,减少嵌套
//
def printAndRemove2(key:String):Unit = {
  if(key==null){
    return
  }
  val value = map.get(key)
  if(value == null){
    return
  }
  println("value="+value)
  map.remove(key)
}

printAndRemove("c")

printAndRemove2("c")

printAndRemove("a")
value=1

printAndRemove2("b")
value=2

上一篇     下一篇
Play2.6.x开始使用Akka HTTP作为默认服务后端

guice循环依赖处理

guice根据名字注入消除歧义

scala Int 与 Integer的区别

pf4j 例子说明

Maven 打包 定制 manifest