Higher-Order Functions in Scala

Scala Apr 25, 2020

As a short recap, Scala is a hybrid language. It has both OOP (object-oriented programming) & FP (functional programming) paradigms implemented within the language.

In mathematics and computer science, a higher-order function is a function that does at least one of the followings:

• takes one or more functions as arguments,
• returns a function as its result.

But... Scala is based on the JVM, how can we pass around functions?

The language's API is providing a trait called FunctionX, where X is a number between zero and 22. Functions are rewritten as objects by the compiler.

And... that's correct! You can have a maximum number of 22 arguments for a function with the default language's API (that feature will be dropped in Scala 3: https://dotty.epfl.ch/docs/reference/dropped-features/limit22.html).

Let's take an example and define a function that accepts an integer as a parameter and returns its 'stringified' version:

``````val stringify = new Function1[Int, String] {
override def apply(value: Int): String = value.toString
}

stringify(42)``````

If we have multiple parameters, we can do something like this:

``````val sum: Function2[Int, Int, Int] = (v1, v2) =>  v1 + v2

sum(4,2)``````

We also took advantage of the short-hand notation in this example. We used a lambda directly and we omitted to create a new Function2 object with the keyword 'new' (like in the previous example).

Now that we understood how functions are defined and how they are working under the hood, what about passing them as arguments?

Imagine the most common use-case:

``List(1,2,3,4,5).map(item => item + 1)``

In this example we used the map operator over a List in order to get another List with all the elements incremented by 1. As we can see, we used a higher-order function: 'item => item + 1'.

If we look over the definition of the map operator:

``def map[B, That](f : scala.Function1[A, B]): That``

We can see that it is expecting to get a Function1 as a parameter.

Conclusion?

All functions in Scala are instances of FunctionX type and they can be easily passed around as first class values.

Cover photo by Roman Mager on Unsplash

Dan-Lucian Roșu

Software engineer passionate about high quality enterprise applications, security and machine learning 👨‍💻

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.