Currying is a technique in functional programming where a function that takes multiple arguments is transformed into a series of functions that each take a single argument. In Scala, this is achieved using multiple parameter lists. Currying can make the code more modular, promote code reusability, and simplify function composition.
Let’s take a simple mathematical example to understand the concept of currying in Scala:
Suppose we want to create a function that takes two integers, ‘x‘ and ‘y‘, and returns the result of the equation ‘ax + by‘, where ‘a‘ and ‘b‘ are constants.
Using the normal method, we might define this function as:
def linearEquation(a: Int, b: Int, x: Int, y: Int): Int = a * x + b * y
With currying (multiple parameter lists), we can define the same function as:
def curriedLinearEquation(a: Int, b: Int)(x: Int, y: Int): Int = a * x + b * y
To make it more clear, let’s see the types of these functions:
linearEquation: (a: Int, b: Int, x: Int, y: Int)Int
curriedLinearEquation: (a: Int, b: Int)(x: Int, y: Int)Int
Now, let’s see how to use these functions:
// Normal function call
val result1 = linearEquation(2, 3, 4, 5) // result1 = 2 * 4 + 3 * 5 = 23
// Curried function call
val result2 = curriedLinearEquation(2, 3)(4, 5) // result2 = 23
The advantage of currying comes into play when we want to apply partial application:
val equationWithConstants = curriedLinearEquation(2, 3) _
‘equationWithConstants‘ is now a partially applied function that takes two ‘Int‘ as its arguments and returns an ‘Int‘. We can reuse this function with different ‘x‘ and ‘y‘ values:
val res1 = equationWithConstants(4, 5) // res1 = 23
val res2 = equationWithConstants(1, 2) // res2 = 2 * 1 + 3 * 2 = 8
In this example, we can see that currying allows us to create a more modular and reusable function in Scala.