Everyone knows how to curry in Scala, less people know why, even less know when. Let’s try and make some sense out of it then!
So it’s inevitable that one day you will read some Scala code and wonder: currying is just like passing more arguments in an over complicated way or am I missing something? Seems unnecessary and complicated and so the inevitable questions comes: why would you ever do that…? Then you search for currying examples and you venture online to see the string concat examples, or maybe integer addition. You come across a few examples like below and can’t wait to use this new feature in production. So… the tale of a code example no one actually ever used goes something like in the snippet below, you see that all over the Internet:
def add(a: Int)(b: Int) = a + b def add4 = add(4) _ add4(10) // 14
If you ask yourself *WHY *— good. Let me explain, because that bugged me for a long time too.
For now, think of currying as nothing more and nothing less than passing arguments to a function in multiple groups.
// one group, three arguments, not currying! def add(one: Int, two: Int, three) = one + two + three // three groups, one argument each - currying! def add(one: Int)(two: Int)(three: Int) = one + two + three
Let’s live with this completely unreal addition example for a moment and let’s talk about function signatures. Once we have a bigger picture, we will move on to real life examples.
Reading Time: 4 minutes A blog on using higher-order functions in Scala.A higher-order function is a function that takes in another function as argument and itself returns some value or function. Some examples of higher-order functions include map, filter, reduce, foreach etc.
Learn what Partial Functions are and how to use them in Scala. See the difference between map and collect when using those on collection.
Functional Programming: Functional Programming is a Declarative style of Programming Paradigm for writing computer programs.
Are functions from programming really functions? If you are reading this, then most probably you already know quite well what functions are in programming.
Learn what are and how to use Higher Order Functions (HOF) in Scala. Leverage best functional programming paradigms in your daily workflow.