如何在Scala中使用ConcurrentHashMap computeIfAbsent()

Fra*_*cis 3 scala concurrenthashmap

ConcurrentHashMap在Scala中使用a ,我想使用该computeIfAbsent()方法,但无法弄清楚第二个参数的语法.有人能告诉我什么是正确的语法?

运行以下代码时

val data = new ConcurrentHashMap[String, LongAdder]

data.computeIfAbsent("bob", k: String => new LongAdder()).increment()
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

Type mismatch, expected: Function[_ >: String, _ <: LongAdder], actual: (String) => Any
Run Code Online (Sandbox Code Playgroud)

提前感谢你

弗朗西斯

Mif*_*eet 6

问题是你正在使用java.util.concurrent.ConcurrentHashMap,它接受java.util.function.Function作为参数,computeIfAbsent()而不是scala.Function1你传递给它的参数.

由于scala不像Java那样支持功能接口的lambda转换(至少没有-Xexperimental标志),你可以通过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()
Run Code Online (Sandbox Code Playgroud)

或者,如果您更频繁地需要它,您可以编写实用程序转换函数或甚至隐式转换:

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
Run Code Online (Sandbox Code Playgroud)