Scala Currying Function

In this tutorial, we will learn about currying functions in scala.Suppose, we have a function that has multiple arguments and this function can be transformed into series of functions where each function has single argument. This process is called currying function in scala.

Let’s understand this with help of examples. You see a currying function below which adds 2 values accepting as arguments.

object sum {
  def main(args: Array[String]): Unit = {
    def add(a:Int, b:Int) = a+b   //Uncurried function
    print(add(2,3))    //Calling function
  }
}
Output: 5

Now, if we want to make it a curried function it will be written as given below. It accepts two list of one Int parameter each. When calling, we need to pass arguments in 2 separate enclosed brackets ().

object sum {
  def main(args: Array[String]): Unit = {
    def add(a:Int) (b:Int) = a+b   //curried function
    print(add(2)(3))    //Calling function
  }
}
Output: 5

We can create series of functions with single arguments and use underscore as placeholder for missing arguments. We can call those newly created function by passing missing whenever required.

object sum {
  def main(args: Array[String]): Unit = {
    def add(a:Int) (b:Int) = a+b   //curried function
    val first = add(2)_   //first function
    val second = first(3) //second function
    print(second)
  }
Output: 5
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...