无法将 [-] 应用于 Scala 中的 AnyVal

Cannot apply [-] to AnyVal in scala

我正在编写一些代码来比较两个双精度值并将一个从字符串解析为双精度。如下所示:

val diffFun0  = (dims:Dims) => (dims.score ==  zippedSubs(dims.dimension_name).trim.toDoubleOption.getOrElse(0))

val diffFun  = (dims:Dims) => (dims.score -  zippedSubs(dims.dimension_name).trim.toDoubleOption.getOrElse(0)).abs > 0.01

//zippedSubs(dims.dimension_name) is double inside string "0.1" or something else


diffLen0 += ods.dimensions.count(diffFun0) //play.sbt.PlayExceptions$CompilationException: Compilation error[Overloaded method value [-] cannot be applied to  (AnyVal)] 

diffLen += ods.dimensions.count(diffFun) //works totally fine

IDE 显示 zippedSubs(dims.dimension_name)。trim.toDoubleOption.getOrElse(0) 是双精度类型,当我们使用 == 运算符时一切正常。但在其他情况下则不然。

您将类型 DoubleInt 混合在一起,结果是 AnyVal。将 getOrElse(0) 替换为 getOrElse(0.0) 并且一切正常。

"0".toDoubleOption.getOrElse(0)
// val res0: AnyVal = 0.0

"0".toDoubleOption.getOrElse(0.0)
// val res0: Double = 0.0