Scala function Corialization (Currying)
Currying refers to the process of changing a function that originally accepts two parameters into a new function that accepts one parameter. The new function returns a function that takes the original second argument as an argument.
Example
First, let’s define a function:
def add(x:Int,y:Int)=x+y
So 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
So when we apply it, we should use it like this: add(1)(2)
in the end, the result is all the same, which is called Corialization.
Realization process
add(1)(2)
in fact, two ordinary functions (non-Corialized functions) arecalled in turn, the first call takes a parameter x and returns a value of afunction type, and the second call uses the parameter y to call the value of this function type.
In essence, it first evolved into such a method:
def add(x:Int)=(y:Int)=>x+y
So what does this function mean? Receives an x as an argument and returns ananonymous function defined as receiving a Int
type parameter y, the body of the function is x+y
. Now let’s call this method.
val result = add(1)
Returns a result
, result
should be an anonymous function (y:Int)=>1+y
So in order to get the results, we continue to call the result
.
val sum = result(2)
The final printed result is 3.
Complete instance
Here 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
}
}
Execute the above code, and the output is as follows:
$ scalac Test.scala
$ scala Test
str1 + str2 = Hello, Scala!