Scala奇怪的隐式拳击转换错误
有人可以告诉我以下原因为何不起作用吗?
Can someone tell me why the following does not work?
object TestObject {
def map(f: (Double, Double) => Double, x2: Array[Double]) = {
val y = x2.zip( x2 )
val z = y.map(f)
z
}
}
产生此错误:
type mismatch; found : (Double, Double) => Double required: ((Double, Double)) => ?
在此代码段中,f
是一个带有两个Double
参数并返回Double
的函数.
您正在尝试通过传递类型为Tuple2[Double,Double]
的单个参数来调用f
.
您可以通过首先更改f
的类型来解决此问题:
In this snippet, f
is a function taking two Double
parameters and returning a Double
.
You are attempting to call f
by passing a single argument of type Tuple2[Double,Double]
.
You can fix this by changing the type of f
in the first place:
object TestObject {
def map(f: ((Double, Double)) => Double, x2: Array[Double]) = {
val y = x2.zip( x2 )
val z = y.map(f)
z
}
}
您也可以将其声明为f: Tuple2[Double, Double] => Double
以便更清楚(这是完全等效的).
You could also declare it as f: Tuple2[Double, Double] => Double
to be clearer (this is entirely equivalent).
相反,您可以这样更改通话:
Conversely, you could change your call like this:
object TestObject {
def map(f: (Double, Double) => Double, x2: Array[Double]) = {
val y = x2.zip( x2 )
val z = y.map(f.tupled)
z
}
}
tupled
自动将您的(Double, Double) => Double
函数转换为Tuple2[Double, Double] => Double
函数.
但是请记住,每次调用TestObject.map
tupled
automagically transforms your (Double, Double) => Double
function into a Tuple2[Double, Double] => Double
function.
Keep in mind however that the conversion will be done on each call to TestObject.map