在Scala中是否可以使用匿名函数创建部分curried函数

时间:2014-01-30 05:33:33

标签: scala anonymous-function currying

我是scala的新手,只是玩一些代码。我在网上找到的一个例子创建了一个curried函数:

    def adder(a: Int, b: Int) = a + b

    var addto = (adder _ ).curried

它有效。但是,当我尝试使用匿名函数替换加法器时...

    var addto = ({(a :Int, b: Int) => a + b} _ ).curried

我收到错误说:

    error: _ must follow method; cannot follow (Int, Int) => Int

知道为什么这不起作用?

2 个答案:

答案 0 :(得分:2)

您不需要占位符(_

scala> var addto = ({(a :Int, b: Int) => a + b}  ).curried
addto: Int => (Int => Int) = <function1>

scala> addto(1)
res0: Int => Int = <function1>

scala> res0(2)
res1: Int = 3

这是因为你已经有了一个函数对象,你可以在其上调用curried

在您之前的案例中

var addto = (adder _ ).curried

在对curried进行操作之前,首先必须将方法转换为函数对象(使用占位符)。

答案 1 :(得分:1)

试试这个

 var addto = ((a :Int, b: Int) => a + b ).curried
相关问题