我正在尝试在List.foreach中调用2参数函数,第一个参数 fixed 用于循环。实际上我想把两个参数的函数变成一个参数的函数,它返回一个参数的函数(如List.foldLeft do)
这不起作用:
private def mathFunc1(a: Double, b: Double) =
println(a + b)
def eval(v: Double) = {
List(1.0, 2.0, 3.0).foreach(mathFunc1(2.1))
}
这有效:
private def mathFunc2(a: Double)(b: Double) =
println(a + b)
def eval(v: Double) = {
List(1.0, 2.0, 3.0).foreach(mathFunc2(2.1))
}
但我不想改变mathFunc1的签名,所以我想做类似的事情:
private def mathFunc1(a: Double, b: Double) =
println(a + b)
def eval(v: Double) = {
List(1.0, 2.0, 3.0).foreach(CONVERT_TWO_PARAMS_TO_ONE_ONE(mathFunc1)(2.1))
}
答案 0 :(得分:18)
private def mathFunc1(a: Double, b: Double) =
println(a + b)
def eval(v: Double) = {
List(1.0, 2.0, 3.0).foreach(mathFunc1(2.1, _))
}
下划线,Scala通配符!
作为一个小小的好奇心,这也会有效:
def eval(v: Double) = {
List(1.0, 2.0, 3.0).foreach(Function.curried(mathFunc1 _)(2.1))
}
甚至:
val curriedMathFunc1 = Function.curried(mathFunc1 _)
def eval(v: Double) = {
List(1.0, 2.0, 3.0).foreach(curriedMathFunc1(2.1))
}