def f(x: Int)(y: Int) = x + y
和有什么区别和def f(x: Int) = (y: Int) => x + y
?
当我将前者与后者同等对待时,REPL 似乎并不高兴:
scala> def f(x: Int)(y: Int) = x + y
f: (x: Int)(y: Int)Int
scala> f(42)
<console>:9: error: missing arguments for method f;
follow this method with `_' if you want to treat it as a partially applied function
f(42)
^
scala> def f(x: Int) = (y: Int) => x + y
f: (x: Int)Int => Int
scala> f(42)
res2: Int => Int = <function1>
具体的区别是什么?我什么时候应该使用哪种形式?
最佳答案
区别在于
def f(x: Int)(y: Int) = x + y
是柯里化(Currying)函数。具有两个参数列表的函数。您可以仅将其与一个参数一起使用,但您需要指定是哪一个。
f(42) _ // this is short for f(42)(_: Int)
将生成一个部分应用函数,其中x
的值为42
。您还可以这样做:
f(_: Int)(42) // note: the first parameter must be used this way
这会将 y
的值设置为 42
。
仅使用几个参数调用柯里化(Currying)函数将生成部分应用函数。
def f(x: Int) = (y: Int) => x + y
是部分应用函数。这里有一个函数,它接受一个参数并返回一个接受一个参数本身的函数。
关于function - 多个参数列表和返回函数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19575454/