我定义了一个函数foo like
def foo(f : (Int, Int) => Int) = f(1,2) // just calling with some default vals
并且可以调用它
foo(_+_)
但是当我尝试使用相同的方式调用一个将 IntPair(自定义类型)作为参数的函数时,我收到错误
error: wrong number of parameters; expected = 1
调用它的正确语法是什么
示例代码
type IntPair = (Int, Int)
def sum(f: (IntPair) => Int): (IntPair) => IntPair = {
def iter(pair: IntPair): IntPair = {
val n = readLine()
print(s"$n+")
if (n != "q") {
val (total, accum) = pair
val p: IntPair = (f(n.toInt, total), accum + 1)
iter(p)
} else {
pair
}
}
iter
}
我可以像这样调用
val f = sum((p : IntPair) => p._1 + p._2) // i want to use here _ syntax
f((0,0))
但不喜欢
val f = sum((_._1 + _._2)) //gives error
最佳答案
scala> def sum(p: ((Int, Int)) => Int) = p((2, 3))
sum: (p: ((Int, Int)) => Int)Int
scala> sum(Function.tupled(_+_))
res4: Int = 5
在 Scala 中参数列表和元组不统一,因此您不能简单地将元组传递给需要多个参数的函数。
sum(_._1 + _._2)
表示 sum((x,y) => x._1 + y._2)
顺便说一句,因此错误.
关于Scala 正确的语法在带有元组的函数文字中使用下划线 ("_"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23449757/