Currying in Scala: A Useful Example

Kadir Malak
Dec 28, 2019 · 2 min read
Photo by Tom Hermans on Unsplash

Currying is the process of taking a function that accepts N arguments and turning it into a function that accepts N-K (N minus K) arguments, missing K arguments are fixed in the resulting function. It’s named after Haskell Curry.

Basic example:

Scala has a separate syntax to ease currying (notice that we first take 2 arguments and then a single argument)

We can even further increase the nesting:

So, you may wonder if this type of functionality has any use in a programming language. Or you may say “All it’s doing is remembering the parameters, I can do this another way”. I’ll show the benefits of currying in a concrete example.

Suppose that we’re running a test code and we want to run the test with a combination of some parameters.

Here is the code without currying:

And here is the one with currying. Notice that:

  • the visual separation between the group of arguments
  • no lambdas used
  • you can clearly see that something is done in a scope

In Scala, if you have a function that takes a single parameter, you may call it like f{argument} (using a {} block) instead of f(argument), if you combine this feature with proper currying, the full magic happens:

Look at it! It almost looks like a macro :) But it’s not. Additional parameters are passed silently.

Look at it! It almost looks like a macro :) But it’s not. Additional parameters are passed silently.

So you may use currying to…

  • separate the parameters passed into logical groups and reuse the middle functions
  • call the final function parameter by parameter as you obtain some values on the way (I’m assuming that you’re passing the resulting functions around)
  • combine it with Scala’s single-parameter block usage - demonstrated above - and obtain macro-like results
  • reduce the syntax when you find yourself returning functions

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade