Explain the concept of 'Currying' in Scala.

Instruction: Define 'Currying' and provide examples of its use in Scala.

Context: This question assesses the candidate's understanding of Currying, a functional programming concept where a function with multiple arguments is transformed into a series of functions, each with a single argument, and its application in Scala.

Updated

Currying transforms a function of multiple arguments into nested single-argument functions. Scala methods with multiple parameter lists support related partial-application patterns, but a method declaration is not itself a function value.

def add(a: Int)(b: Int): Int = a + b

@main def curryingExample(): Unit = {
  val addFive: Int => Int = add(5)
  val twoArguments: (Int, Int) => Int = (a, b) => a + b
  val curried: Int => Int => Int = twoArguments.curried
  val restored: (Int, Int) => Int = Function.uncurried(curried)
  assert(add(2)(3) == 5)
  assert(addFive(7) == 12)
  assert(curried(2)(3) == 5 && restored(2, 3) == 5)
}

In this Scala 3 example, the expected function type lets the compiler convert the remaining method parameter list into a function. curried demonstrates the transformation of a two-argument function value explicitly. Partial application fixes arguments, such as 5; currying changes the shape of argument passing. Multiple parameter lists

These patterns can separate configuration from the inputs handled repeatedly. They do not cache results, change authorization rules or guarantee faster execution. Avoid defining otherwise identical curried and uncurried methods with the same name when their erased JVM signatures would collide.

Related Questions