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. First, let’s define a function: So when we apply it, we should use it like this: Now let’s transform this function: So when we apply it, we should use it like this: In essence, it first evolved into such a method: So what does this function mean? Receives an x as an argument and returns ananonymous function defined as receiving a Returns a So in order to get the results, we continue to call the The final printed result is 3. Here is a complete example: Execute the above code, and the output is as follows: 8.25.1. Example #
def add(x:Int,y:Int)=x+y
add(1,2)
def add(x:Int)(y:Int) = x + y
add(1)(2)
in the end, the result is all the same, which is called Corialization. 8.25.2. 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.def add(x:Int)=(y:Int)=>x+y
Int
type parameter y, the body of the function is
x+y
. Now let’s call this method.val result = add(1)
result
,
result
should be an anonymous function
(y:Int)=>1+y
result
.val sum = result(2)
8.25.3. Complete instance #
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
}
}
$ scalac Test.scala
$ scala Test
str1 + str2 = Hello, Scala!