Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Scala Function Currying

Scala Function Currying

Scala functions Scala Functions

Currying refers to the process of turning a function that originally takes two arguments into a new function that takes one argument. The new function returns a function that takes the original second argument as its parameter.

Example

First, we define a function:



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

Then when we apply it, we use it like this: add(1,2)

Now let's transform this function a bit:



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

Then when we apply it, we use it like this: add(1)(2); the final result is still 3. This approach (process) is called currying.

Implementation process

add(1)(2) actually calls two ordinary functions (non-curried functions) in sequence: the first call uses one argument x and returns a function-typed value, and the second call uses argument y to invoke that function-typed value.

In essence, it first evolves into a method like this:



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

What does this function mean? It takes an x as a parameter and returns an anonymous function defined as: takes an Int parameter y, with body x+y. Now let's call this method.



val result = add(1) 

It returns a result, whose value should be an anonymous function: (y:Int)=>1+y

So to get the final result, we call result again.



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

   }

}

The output of the code above is:



$ scalac Test.scala

$ scala Test

str1 + str2 = Hello, Scala!

Scala functions Scala Functions