higher-order-functions-in-scala

admin

2/17/2025

  Scala Higher-Order Function Example

Go Back

Higher Order Functions in Scala: Examples, Features, and Best Practices

Updated: February 2025 | By Shubham Mishra 

      Scala Higher-Order Function Example

What Are Higher Order Functions?

A higher order function is a function that:

  • Takes one or more functions as parameters.
  • Returns a function as a result.

This concept is not unique to Scala—it’s also found in languages like Java 8+ (e.g., lambda expressions). However, Scala’s functional programming capabilities make it particularly well-suited for higher order functions.The terminology can get a bit confusing at this point, and we use the phrase “higher order function” for both methods and functions that take functions as parameters or that return a function.

Example: Higher Order Function in Scala

Let’s start with a simple example of a higher order function in Scala. The map function is one of the most common higher order functions available for collections.


val mySalaries = Seq(70000, 20000, 40000)
val doubleSalary = (x: Int) => x * 2
val newSalaries = mySalaries.map(doubleSalary) // List(140000, 40000, 80000)
    

In this example:

  • map is a higher order function.
  • doubleSalary is a function passed as an argument to map.

Practical Example: Salary Promotion Maker

Let’s create a more advanced example to demonstrate the power of higher order functions. Suppose we want to apply different types of salary promotions:


object SalaryPromotionMaker {
  def smallPromotion(salaries: List[Double]): List[Double] = salaries.map(salary => salary * 1.1)
  def greatPromotion(salaries: List[Double]): List[Double] = salaries.map(salary => salary * math.log(salary))
  def hugePromotion(salaries: List[Double]): List[Double] = salaries.map(salary => salary * salary)
}
    

Notice how each method varies only by the multiplication factor. We can simplify this by extracting the repeated code into a higher order function:


object SalaryPromotionMaker {
  private def promotion(salaries: List[Double], promotionFunction: Double => Double): List[Double] =
    salaries.map(promotionFunction)

  def smallPromotion(salaries: List[Double]): List[Double] = promotion(salaries, salary => salary * 1.1)
  def greatPromotion(salaries: List[Double]): List[Double] = promotion(salaries, salary => salary * math.log(salary))
  def hugePromotion(salaries: List[Double]): List[Double] = promotion(salaries, salary => salary * salary)
}
    

Here, promotion is a higher order function that takes a function (promotionFunction) as a parameter.

Passing Functions as Arguments

You can pass functions as arguments to other functions. This is useful when you want to provide different behaviors dynamically.


// Higher-order function that takes a function f and two integers as arguments
def operate(f: (Int, Int) => Int, x: Int, y: Int): Int = {
  f(x, y)
}

// Define functions to pass as arguments
def add(a: Int, b: Int): Int = a + b
def multiply(a: Int, b: Int): Int = a * b

// Call the higher-order function with different functions
val resultAdd = operate(add, 3, 5)        // Result: 8 (3 + 5)
val resultMultiply = operate(multiply, 3, 5)   // Result: 15 (3 * 5)
println(resultAdd)
println(resultMultiply)
    

Features of Higher Order Functions

Higher order functions offer several benefits:

  • Reusable Code: Write generic functions that can be reused across different scenarios.
  • Abstraction: Abstract complex logic into simpler, composable functions.
  • Flexibility: Dynamically change behavior by passing different functions.
  • Functional Composition: Combine smaller functions to build more complex behaviors.

Best Practices for Using Higher Order Functions

  1. Keep Functions Small: Higher order functions work best when the functions passed as arguments are small and focused.
  2. Use Descriptive Names: Name your functions and parameters clearly to improve readability.
  3. Leverage Scala’s Standard Library: Use built-in higher order functions like map, filter, and reduce.
  4. Test Thoroughly: Higher order functions can introduce complexity, so ensure you test edge cases.

Frequently Asked Questions (FAQs)

1. What is a higher order function in Scala?

A higher order function is a function that takes one or more functions as parameters or returns a function as a result.

2. What are some examples of higher order functions in Scala?

Examples include map, filter, reduce, and custom functions like promotion in the salary example above.

3. Why use higher order functions?

They promote code reuse, abstraction, and flexibility, making your code more modular and easier to maintain.

4. Can higher order functions return functions?

Yes, higher order functions can return functions as results.

Conclusion

Higher order functions are a cornerstone of functional programming in Scala. They allow you to write reusable, abstract, and flexible code, making your programs more modular and easier to maintain. By mastering higher order functions, you can unlock the full potential of Scala’s functional programming capabilities.

Start experimenting with higher order functions today! Try creating your own examples, explore Scala’s standard library, and build more expressive and efficient code.

Table of content