第一种形式的工作原理是什么,而不是第二种?
scala> val d = (a: Int, b: Int) => a + b
d: (Int, Int) => Int = <function2>
scala> val d = (a: Int)(b: Int) => a + b
<console>:1: error: not a legal formal parameter.
Note: Tuples cannot be directly destructured in method or function parameters.
Either create a single parameter accepting the Tuple1,
or consider a pattern matching anonymous function: `{ case (param1, param1) => ... }
val d=(a:Int)(b:Int)=>a+b
答案 0 :(得分:3)
因为函数声明不允许使用多个参数列表。如果你想要一个函数,你可以:
scala> val d: Int => Int => Int = a => b => a + b
d: Int => (Int => Int) = $$Lambda$1106/512934838@6ef4cbe1
scala> val f = d(3)
f: Int => Int = $$Lambda$1109/1933965693@7e2c6702
scala> f(4)
res6: Int = 7
您还可以创建单个参数列表并部分应用它:
scala> val d = (a: Int, b: Int) => a + b
d: (Int, Int) => Int = $$Lambda$1064/586164630@7c8874ef
scala> d(4, _: Int)
res2: Int => Int = $$Lambda$1079/2135563436@4a1a412e
我们部分应用了d
和4,我们找回了一个函数Int => Int
,这意味着当我们提供下一个参数时,我们会得到结果:
scala> res2(3)
res3: Int = 7
我们还可以创建一个命名方法,并使用eta-expansion从中创建一个curried函数:
scala> def add(i: Int)(j: Int): Int = i + j
add: (i: Int)(j: Int)Int
scala> val curriedAdd = add _
curriedAdd: Int => (Int => Int) = $$Lambda$1115/287609100@f849027
scala> val onlyOneArgumentLeft = curriedAdd(1)
onlyOneArgumentLeft: Int => Int = $$Lambda$1116/1700143613@77e9dca8
scala> onlyOneArgumentLeft(2)
res8: Int = 3
答案 1 :(得分:1)
可以进行功能调整。
val curryFunc = (a: Int) => (b: Int) => a + b
curryFunc现在具有Int => (Int => Int)