Labels

Thursday, April 14, 2022

Currying function in Scala (Class -35)

The name Currying may seem obscure but the technique is named after Haskell Curry (for whom the Haskell programming language is named). Grouping of Parameters together is called Currying.

A currying function is a transforming function with multiple arguments transformed into single arguments. A currying function takes two arguments into a function that takes only a single argument.


There are two syntaxes to define the currying functions in Scala.

def functionName (arg1) = (arg2) => operation

  def functionName(arg1) (arg2) = operation



In the first syntax, the function takes arg1 which equals arg2 and then the operation is performed.

The first single argument is the original function argument. This function returns another function that takes the second of the original function. This chaining continuous for all arguments of the function.

The last function in this chain does the actual word of the function call.

5 arguments writing as group:


Why is this useful? It is because we can provide a value to use for the first function before we wish to provide a value for the second function. As the result of providing the value for the first function is to return a function value to use with the second, we can essentially store that functions and its subsequent invocation for later use.

No comments:

Post a Comment