Scala提供了正确的语法,可以在带有元组的函数文本中使用下划线(“uquot;”)
我定义了一个类似foo的函数Scala提供了正确的语法,可以在带有元组的函数文本中使用下划线(“uquot;”),scala,Scala,我定义了一个类似foo的函数 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 = (I
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中,参数列表和元组是不统一的,因此不能简单地将元组传递给需要多个参数的函数
sum(u.\u 1+u.\u 2)
表示sum((x,y)=>x.\u 1+y.\u 2)
btw,因此出现错误
scala> def sum(p: ((Int, Int)) => Int) = p((2, 3))
sum: (p: ((Int, Int)) => Int)Int
scala> sum(Function.tupled(_+_))
res4: Int = 5