譁眾取寵
讓我們定義 2 個引數的函式:
def add: (Int, Int) => Int = (x,y) => x + y
val three = add(1,2)
Currying add
將它轉換為一個函式,它接受一個 Int
並返回一個函式 (從一個 Int
到一個 Int
)
val addCurried: (Int) => (Int => Int) = add2.curried
// ^~~ take *one* Int
// ^~~~ return a *function* from Int to Int
val add1: Int => Int = addCurried(1)
val three: Int = add1(2)
val allInOneGo: Int = addCurried(1)(2)
你可以將此概念應用於任何帶有多個引數的函式。假設一個帶有多個引數的函式,將它轉換為一系列帶有一個引數的函式應用程式 :
def add3: (Int, Int, Int) => Int = (a,b,c) => a + b + c + d
def add3Curr: Int => (Int => (Int => Int)) = add3.curried
val x = add3Curr(1)(2)(42)