What is Currying?
Currying simply means converting a function taking more than one parameter can be into a series of functions with each taking one parameter. Example:
result = f(x, y, z) // normal function
// curried version
f1 = f(x)
f2 = f1(y)
result = f2(z)
// alternatively
result = f(x)(y)(z)
As we can see, a function that takes 3 parameters is converted into a series of function calls taking one parameter each.
val add: (Int, Int, Int) => Int = (a, b, c) => a + b + c
val curriedAdd: Int => Int => Int => Int = a => b => c => a + b + c
The type of add is (Int, Int, Int) => Int [<function3>]
The type of curriedAdd is (Int => (Int => (Int => Int)) [<function1>]
Another thing to note is that this is not a Scala-specific feature and many other languages like JavaScript also support currying.
Currying v/s Partially Applied Functions
The 2 concepts of currying and Partially Applied Functions are related but they are not the same.
Currying is, as mentioned, a technique where a function with multiple parameters can be converted into a series of function calls with one parameter each.
A partially applied function is a function that the programmer creates by supplying fewer parameters than the original function requires.
For example for the above add function:
add(3, 4, 5) // normal function
curriedAdd(3)(4)(5) // curried function
// Partially Applied version of add function
val addOne: (Int, Int) => Int = add(1, _, _)
So, while both are related to functions having multiple parameter groups, curried functions are stricter in the sense that they take only one parameter each.
Partially applied functions, on the other hand, are more flexible in terms of the number of parameters.
“curried” method
There is a special curried method in FunctionX classes that we use to convert normal functions into their curried version.
For example in Function3 trait, it is defined like this:
def curried: T1 => T2 => T3 => R = {
(x1: T1) => (x2: T2) => (x3: T3) => apply(x1, x2, x3)
}
This is how we use this method on our add function
val curriedFunction: Int => Int => Int => Int = add.curried
println(curriedFunction(2)(3)(4)) // OUTPUT: 9
Conclusion
Currying is simply a design technique to make functions. It is something we usually accept as a concept that is “nice to know”.
A programmer can work without using this technique. However, we use it along with Partially applied functions in situations where we require multiple parameters.
It often helps is reducing code duplicity and helps in achieving DRY (Don’t Repeat Yourself) principle
1 thought on “Currying in Scala for complete Beginners2 min read”
Comments are closed.