2014-01-30 73 views
1

我是scala的新手,只是玩弄一些代码。我从一个例子中创建了一个curried函数,我在网上找到这行: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

你不需要占位符(_

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之前的方法将一个函数对象转换。

+0

很酷谢谢。加法器是一种方法而不是一种功能? –

+0

'def'定义了一个方法,而'val'和'var'产生了一个函数。 –

+0

'加法器'是一种方法。当我们说功能,即当你做'加法器_'时,你会得到一个'Function2 [Int,Int,Int]'对象。 – Jatin

1

试试这个

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