Scala Function Currying
Currying refers to the process of transforming a function that originally takes two parameters into a new function that takes one parameter. The new function returns a function that takes the original second parameter as its argument.
Examples
First, we define a function:
def add(x:Int,y:Int)=x+y
Then when we apply it, we should use it like this: add(1,2)
Now let's transform this function:
def add(x:Int)(y:Int) = x + y
Then when we apply it, we should use it like this: add(1)(2), and the final result is still 3. This method (process) is called currying.
Implementation Process
add(1)(2) actually calls two ordinary functions (non-curried functions) in sequence. The first call uses one parameter x and returns a function-type value, and the second call uses parameter y to invoke this function-type value.
In essence, it first evolves into a method like this:
def add(x:Int)=(y:Int)=>x+y
So what does this function mean? It takes x as a parameter and returns an anonymous function. The definition of this anonymous function is: it takes an Int parameter y, and the function body is x+y. Now let's call this method.
val result = add(1)
It returns a result, and the value of result should be an anonymous function: (y:Int)=>1+y
So in order to get the result, we continue to call result.
val sum = result(2)
The final printed result is 3.
Complete Example
Below is a complete example:
object Test {
def main(args: Array[String]) {
val str1:String = "Hello, "
val str2:String = "Scala!"
println( "str1 + str2 = " + strcat(str1)(str2) )
}
def strcat(s1: String)(s2: String) = {
s1 + s2
}
}
Executing the above code produces the following output:
$ scalac Test.scala $ scala Test str1 + str2 = Hello, Scala!Other Extensions
Scala Functions