Currying Function in Scala

Currying in Scala is a technique of transforming a function that takes multiple arguments into a function that takes only one argument. To achieve this we will convert the function having list of parameters to a function with chain of functions one for each parameter.

Let's take a look at some code snippets of Currying functions.

Below is a code snippet that done without using Currying:

object CurryingFunctions { 
  def addition (a: Int, b: Int) = a + b

  def main(args: Array[String]) { 
    println(addition(4,5))
  } 
}

Below is another code of the same addition function with Currying:

object CurryingFunctions{ 
  def addition (a: Int) (b: Int) = a + b; //Currying

  def main(args: Array[String]) { 
    println(addition(4)(5)); 
  } 
}

 

The same function can be called using Partially applied functions:

Partially applied function means applying some of the parameters of function. Then we will get a partially applied function that can be used later.

object CurryingFunctions { 

  def addition(a: Int) (b: Int) = a + b; 

  def main(args: Array[String]) { 
    val total = addition(5)_ //Partially applied function
    println(total(10)) //Output: 15
  } 
}

 

Please let us know your thoughts about this post..

Leave a Reply

Your email address will not be published. Required fields are marked *