Scala, Currying on multi parameter-group method?

▼魔方 西西 提交于 2019-12-24 04:30:24

问题


I am wondering if it is possible to use currying on multi parameter-group functions :

scala> def sum(a: Int)(b: Int): Int = { a+b }
sum: (a: Int)(b: Int)Int

scala> sum(3)(4)
res2: Int = 7

scala> val partFunc = sum(3) _
partFunc: Int => Int = <function1>

scala> partFunc(4)
res3: Int = 7

scala> val partFunc2 = sum _ _
<console>:1: error: ';' expected but '_' found.
       val partFunc2 = sum _ _
                             ^

scala> val partFunc2 = (sum _) _
<console>:8: error: _ must follow method; cannot follow Int => (Int => Int)
       val partFunc2 = (sum _) _

回答1:


Writing simply sum _ does not yet have anything to do with the arguments of sum, but simply distinguishes the function object sum from an application of the function.

Hence, you can write:

scala> val partFunc2 = sum _
partFunc2: Int => (Int => Int) = <function1>

As you can see from the type information, this is already the curried version of sum which takes two Int parameters.

Of course, you can then proceed as before with partFunc2(4) being of type Int => Int and so on.




回答2:


You can do it like this:

val partFunc2 = sum _

or like this:

val partFunc2 = sum(3) _


来源:https://stackoverflow.com/questions/10880982/scala-currying-on-multi-parameter-group-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!