Skip to content

Scala – Curried Function!

At this moment I do not have a personal relationship with a computer.

Janet Reno

In Scala, a curried function is a function that takes multiple arguments, but instead of taking them all at once, it takes them one at a time and returns a new function that takes the next argument. The process of converting a function that takes multiple arguments into a curried function is called currying.

Here’s an example of a curried function in Scala:

def add(x: Int)(y: Int): Int = x + y

val add2 = add(2) _

val result = add2(3)
println(result) // Output: 5

In this example, add is a curried function that takes an integer x as its first argument and returns a new function that takes an integer y as its second argument and returns their sum. We can create a new function add2 by calling the add function with the first argument 2 and using the underscore _ to indicate that we are not providing a value for the second argument yet. The resulting function takes a single integer argument and returns their sum, by adding the value 2 to the argument.

When we call the add2 function with the argument 3, it returns the expected result of 5. This is because the value 2 is already provided by the curried function.

Curried functions can be useful when we want to create new functions that are based on existing functions, but with some of the arguments already filled in. They can also be useful for creating functions that are more easily composable and reusable.

Note that curried functions are different from partially applied functions, which are functions that are created by providing some, but not all, of the arguments to a function. Curried functions are functions that are defined to take their arguments one at a time, while partially applied functions are functions that are created by providing some, but not all, of the arguments to a function.

Published inPersonal PostsScalaTechnical Posts