如何在Scala中使用ConcurrentHashMap computeIfAbsent()
我在Scala中使用了一个如何在Scala中使用ConcurrentHashMap computeIfAbsent(),scala,concurrenthashmap,Scala,Concurrenthashmap,我在Scala中使用了一个ConcurrentHashMap,我想使用ComputeFabSent()方法,但无法理解第二个参数的语法。有人能告诉我正确的语法是什么吗 当运行以下代码时 val data = new ConcurrentHashMap[String, LongAdder] data.computeIfAbsent("bob", k: String => new LongAdder()).increment() 我得到以下错误 Type mismatch, expecte
ConcurrentHashMap
,我想使用ComputeFabSent()
方法,但无法理解第二个参数的语法。有人能告诉我正确的语法是什么吗
当运行以下代码时
val data = new ConcurrentHashMap[String, LongAdder]
data.computeIfAbsent("bob", k: String => new LongAdder()).increment()
我得到以下错误
Type mismatch, expected: Function[_ >: String, _ <: LongAdder], actual: (String) => Any
类型不匹配,应为:函数[\u>:String,\uu任何
先谢谢你
Francis问题在于您使用的是
java.util.concurrent.ConcurrentHashMap
,它接受java.util.function.function
作为ComputeFabSent()
的参数,而不是传递给它的scala.Function1
由于scala不像Java那样支持函数接口的lambda转换(至少没有),您可以通过显式实现Java.util.function.function
来解决这个问题:
val data = new ConcurrentHashMap[String, LongAdder]
val adderSupplier = new java.util.function.Function[String, LongAdder]() {
override def apply(t: String): LongAdder = new LongAdder()
}
data.computeIfAbsent("bob", adderSupplier).increment()
或者,如果您更经常需要此功能,可以编写实用程序转换函数,甚至隐式转换:
object FunctionConverter {
implicit def scalaFunctionToJava[From, To](function: (From) => To): java.util.function.Function[From, To] = {
new java.util.function.Function[From, To] {
override def apply(input: From): To = function(input)
}
}
}
import FunctionConverter._
val data = new ConcurrentHashMap[String, LongAdder]()
data.computeIfAbsent("bob", (k: String) => new LongAdder()) // <- implicit conversion applied here
对象函数转换器{
隐式def scalaFunctionToJava[From,To](函数:(From)=>To):java.util.function.function[From,To]={
新的java.util.function.function[From,To]{
覆盖def应用(输入:从):到=功能(输入)
}
}
}
导入函数转换器_
val data=新的ConcurrentHashMap[字符串,长加法器]()
data.computeIfAbsent(“bob”,(k:String)=>new LongAdder())/如果启用-xeexperimental
标志,则可以使用scala匿名函数表示法:
scala> val data = new java.util.concurrent.ConcurrentHashMap[String, Int]
data: java.util.concurrent.ConcurrentHashMap[String,Int] = {}
scala> data.computeIfAbsent("bob", _.size)
res0: Int = 3
请注意,您仍然无法通过常规scala函数
scala> val f: String => Int = _.size
f: String => Int = <function1>
scala> data.computeIfAbsent("bob", f)
<console>:13: error: type mismatch;
found : String => Int
required: java.util.function.Function[_ >: String, _ <: Int]
data.computeIfAbsent("bob", f)
^
scala> def a(s: String): Int = s.size
a: (s: String)Int
scala> data.computeIfAbsent("bob", a)
res3: Int = 3