Currying in scala

scala

Currying is a concept in functional programming. It’s the process converting function evaluation with multiple arguments to the evaluation of a series of functions with single argument. It turns a normal function to a function accept one parameter return another function.

See below code, sum’s type is (Int, Int) => Int, sumCurried’s type is Int => Int => Int, it’s the curried version of sum.

def sum(a: Int, b: Int): Int = a + b
def sumCurried(a: Int)(b: Int): Int = a + b

To curry a function in Scala, you can use eta expansion and function partial application language feature.

Eta expansion allows you to convert a method to a function literal. Function literal in Scala is actually a FunctionX(Function1, Function2…) instance. So that it can be passed in as parameter or returned out directly. That’s how Scala implement function as value.

Function partial application is to create a new function with one or more function literal arguments fixed.

def sum(a: Int, b:Int): Int = a + b
val f: (Int, Int) => Int = sum // f is a function literal, an instance of Function2
val curried: Int => Int => Int = f.curried // currying, curried is a method of Function2
val g: Int => Int = f(2,_) // partial application, _ is placeholder
// auto Eta expansion inside
val g_ : Int => Int = sum(2, _)//U can also partial apply sum
val uncurried:(Int, Int) => Int = Function.uncurried(curried) // uncurrying