Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the responsive-lightbox domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the hueman domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114
Scala Currying Function - Testingpool

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