Currying in Scala

Thu, Jul 31, 2014

Programming Scala #programming #scala

Currying is a process to transform a function that takes multiple parameters into functions that take one parameter each and chaining to each other accordingly. Each function will return a function value to the next function and so on.

For example, here is a method to calculate the value of x(base) to the power of y(exponent).

def power(exponent:Double, base:Double) => Math.pow(base, exponent)
println(power(2d, 3d))
// 9.0

This method will take in 2 parameters. To curry up this method, there are 2 ways of doing it.

//1st way
def power(exponent:Double) = (base:Double) => Math.pow(base, exponent)

// -- OR --

//2nd way
val power = (exponent:Double, base:Double) => Math.pow(base, exponent)
//ok this is a funny name
val curriedPower = power.curried

How to use?

// for the 1st way
val powerToTwo = power(2d)
//for the second way
val powerToThree = curriedPower(3d)
//prints 4.0
//prints 27.0

As we can see, by using currying, we can actually create methods with predefined parameter and reuse it. And we can also create methods with more meaningful name that implies what it does, from the example above, “powerToTwo” sounds much concise compare to “Math.pow(4d, 2d)” (exponent is at the second parameter).