Latest web development tutorials

Scala function currying (Currying)

Scala function Scala function

Currying (Currying) refers to the original function accepts two parameters into a new function accepts a parameter of the process. A new function returns the second parameter is the original function of the parameter.

Examples

First, we define a function:

def add(x:Int,y:Int)=x+y

So when we applied, it should be used like this: add (1,2)

Now we look at this function change shape:

def add(x:Int)(y:Int) = x + y

So when we applied, it should be used like this: add (1) (2), the final results are the same is 3, this approach (process) is called currying.

Implementation process

add (1) (2) is actually a function in turn calls two ordinary (non-curried function), the first call using a parameter x, the return value of a function type, and the second parameter y call this function type value.

The first essentially evolved into a method:

def add(x:Int)=(y:Int)=>x+y

Then this function is what does that mean? Receiving a x as a parameter and returns an anonymous function, the definition of the anonymous function is: receiving an Int argument y, the function body is x + y. Now we call this method.

val result = add(1) 

Returns a result, the value of that result should be an anonymous function: (y: Int) => 1 + y

So in order to get results, we continue to call the result.

val sum = result(2)

Finally, print out result is 3.

Complete example

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
   }
}

Implementation of the above code, the output is:

$ scalac Test.scala
$ scala Test
str1 + str2 = Hello, Scala!

Scala function Scala function