
上QQ阅读APP看书,第一时间看更新
Function currying
Function currying means converting a function's single parameters list into a multiple parameters list. Take a look at the following code example:
scala> def add(a:Int,b:Int,c:Int) = a + b + c add: (a: Int, b: Int, c: Int)Int scala> add(1,2,3) res2: Int = 6 scala> def add(a:Int)(b:Int)(c:Int) = a + b + c add: (a: Int)(b: Int)(c: Int)Int scala> add(1,2,3) <console>:16: error: too many arguments (3) for method add: (a: Int)(b: Int)(c: Int)Int add(1,2,3) ^ scala> add(1)(2)(3) res4: Int = 6
One of the important use cases of currying is to support implicit parameters.
The following examples demonstrate how currying supports implicit parameters:
scala> def add(x: Int, implicit y: Int) = x + y <console>:1: error: identifier expected but 'implicit' found. def add(x: Int, implicit y: Int) = x + y ^ scala> def add(x: Int) (implicit y: Int) = x + y add: (x: Int)(implicit y: Int)Int scala> implicit val a:Int = 12 a: Int = 12 scala> add(11) res1: Int = 23