2014-01-30 74 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 
相關問題