WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Scala · Basic · question 18 of 100

Explain the concept of currying in Scala with an example.?

📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Scala interview — then scores it.
📞 Practice Scala — free 15 min
📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

All 100 Scala questions · All topics