Scala Tutorial - Learn How To Create Higher Order Function - Function As Parameter

By Nadim Bahadoor | Last updated: March 16, 2018 at 11:33 am

Overview

In this tutorial, we will learn how to create Higher Order Function which is a function that takes another function as its parameter.

 

In addition, we will show how to pass-through an anonymous function or a regular def function to the Higher Order Function.

Steps

1. Review how to define function with curried parameter groups

Let's start by reviewing the totalCost() function from the previous tutorial on Curried Function With Parameter Groups.


println("Step 1: Review how to define function with curried parameter groups")
def totalCost(donutType: String)(quantity: Int)(discount: Double): Double = {
  println(s"Calculating total cost for $quantity $donutType with ${discount * 100}% discount")
  val totalCost = 2.50 * quantity
  totalCost - (totalCost * discount)
}

NOTE:

  • The totalCost() function has a discount parameter which could be a potential candidate to pass-through a function to apply the discount logic.
  • In other words, let's redefine the totalCost() function to take another function for the discount parameter a shown below in Step 2.

2. How to define a higher order function which takes another function as parameter

A Higher Order Function is a function which takes another function as its parameters.

 

Instead of the discount parameter, let's define a parameter which is a function that has an input parameter of type Double and will also return a type of Double using the syntax (f: Double => Double)


println("\nStep 2: How to define a higher order function which takes another function as parameter")
def totalCostWithDiscountFunctionParameter(donutType: String)(quantity: Int)(f: Double => Double): Double = {
  println(s"Calculating total cost for $quantity $donutType")
  val totalCost = 2.50 * quantity
  f(totalCost)
}

NOTE:

  • In the totalCostWithDiscountFunctionParameter() function, you call the function f by passing it the totalCost value
    f(totalCost)
  • This function f will be provided at the time when you call thetotalCostWithDiscountFunctionParameter() function.

3. How to call higher order function and pass an anonymous function as parameter

The totalCostWithDiscountFunctionParameter() Higher Order Function defined in Step 2 now expects a discount function to be passed-through.

 

For this example, we will pass through an anonymous function which will apply the discount logic to the totalCost value as shown below:


println("\nStep 3: How to call higher order function and pass an anonymous function as parameter")
  val totalCostOf5Donuts = totalCostWithDiscountFunctionParameter("Glazed Donut")(5){totalCost =>
  val discount = 2 // assume you fetch discount from database
  totalCost - discount
}
println(s"Total cost of 5 Glazed Donuts with anonymous discount function = $totalCostOf5Donuts")

You should see the following output when you run your Scala application in IntelliJ:


Step 3: How to call higher order function and pass an anonymous function as parameter
Calculating total cost for 5 Glazed Donut
Total cost of 5 Glazed Donuts with anonymous discount function = 10.5

 

4. How to define and pass a function to a higher order function

A better approach to Step 3 is to pass-through a common discount function which would encapsulate the discount logic instead of providing an anonymous function.

 

To this end, let's create a function named applyDiscount as follows:


println("\nStep 4: How to define and pass a function to a higher order function")
def applyDiscount(totalCost: Double): Double = {
  val discount = 2 // assume you fetch discount from database
  totalCost - discount
}

You can then pass-through the applyDiscount() function to the totalCostWithDiscountFunctionParameter() function as follows:


println(s"Total cost of 5 Glazed Donuts with discount function = ${totalCostWithDiscountFunctionParameter("Glazed Donut")(5)(applyDiscount(_))}")

You should see the following output when you run your Scala application in IntelliJ:


Step 4: How to define and pass a function to a higher order function
Calculating total cost for 5 Glazed Donut
Total cost of 5 Glazed Donuts with discount function = 10.5

 

This concludes our tutorial on Learn How To Create Higher Order Function - Function As Parameter and I hope you've found it useful!

 

Stay in touch via Facebook and Twitter for upcoming tutorials!

 

Don't forget to like and share this page :)

Summary

In this tutorial, we went over the following:

  • How to define function with curried parameter groups
  • How to define a Higher Order Function which takes another function as parameter
  • How to call Higher Order Function and pass an anonymous function as parameter
  • How to define and pass-through a function to a Higher Order Function

Tip

  • You can refer to the Scala documentation for additional information on Higher Order Functions.

Source Code

The source code is available on the allaboutscala GitHub repository.

 

What's Next

In the next tutorial, I will continue the discussion on Higher Order Function and show you how to define by-name functions.

Nadim Bahadoor on FacebookNadim Bahadoor on GithubNadim Bahadoor on LinkedinNadim Bahadoor on Twitter
Nadim Bahadoor
Technology and Finance Consultant with over 14 years of hands-on experience building large scale systems in the Financial (Electronic Trading Platforms), Risk, Insurance and Life Science sectors. I am self-driven and passionate about Finance, Distributed Systems, Functional Programming, Big Data, Semantic Data (Graph) and Machine Learning.
Other allaboutscala.com tutorials you may like: