Home » Scala language

Currying function in Scala

A function that has multiple functions each with one argument chained as an argument of one function. In this Scala tutorial, we will discuss currying function in Scala and how they are implemented using an example?
Submitted by Shivang Yadav, on June 28, 2019

Currying function in Scala

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

Syntax explanation:

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.


object MyClass {

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

      def main(args: Array[String]) {
         println("sum of x + y = " + add(25)(10) );
         println("sum of a + b = " + add(214)(4564) );


sum of x + y = 35
sum of a + b = 4778

Code explanation:

The above code defines and uses a currying function named add this function simply adds two numbers and return their addition. But is defined based on how a currying function is defined. The call also sends two numbers like two different functions in the function call.

Currying is a little bit tricky concept and you need to properly understand it to master over this. But this concept is useful while programming some big programs in Scala.

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.