Higher Order Functions (HOF) in Scala are the very core of this functional programming language. Scala treats functions as a first class citizens. Those functions can be passed around and treated like any other data types. Specifically, Scala allows to pass functions as parameters to other functions. That is known as Higher Order Function (HOF), and that’s what this post will explain in detail.

What is Higher Order Function (HOF) in Scala?

Higher order functions take other functions as parameters or return a function as a result.

scala-lang.org

As the definition above suggests, the functions in Scala are treated equally to typical data types like integers or strings. Moreover, a function can be assigned to a variable or value, and then passed around like a typical parameter. The HOF in Scala are quite frequently found in collection methods. The filter method of let’s say List class can take such function, which is then treated equally to an old school predicate. Let’s see how those functions can be manipulated in practice.

Functions as a Data Type

Chapter above explained that functions can be treated as standard data types in Scala. Let’s see how this works in practice. Let’s assume that we want a functions that calculates the exponent of an arbitrary number.

// Bring a value to the power of two using lambdas (single abstract method)
val toPowerOfTwo = (x: Int) => x * x

// Same as above, but uses using verbose approach
val toPowerOfTwoVerbose = new Function1[Int, Int] {
  override def apply(value: Int): Int = value * value
}
val toPowerOfThree = (x: Int) => x * x * x

The two approaches shown above construct the same type of a function. Our desired function should take one parameter of int and return a result of an int. As you have probably already spotted, both functions have been assigned to values. This way, they can be passed around no differently to let’s say integer or double type value.

The first implementation uses widely known as lambda or single abstract method. The second implementation uses the trait Function1, on which an apply method is overridden. Scala provides more variants of this Function trait, like Function2, or Function3, taking 2 or 3 parameters respectively.

Now, with those functions you can primarily do two things: call them or give as a parameter to another function. That’s what the next chapter will focus on.

#programming #coding #backend #functional-programming #scala #function

Higher Order Functions (HOF) in Scala
1.45 GEEK