Table of contents
1.
Introduction
2.
What is Scala
3.
Higher Order Functions in Scala
4.
Anonymous Function
5.
Function as Parameter
5.1.
Using map
5.2.
Using flatMap
5.3.
Using filter
5.4.
Using reduce
5.5.
Using fold
6.
Functions Returning Functions
7.
Frequently Asked Questions
7.1.
What does this _* mean in Scala?
7.2.
Is lambda a higher-order function?
7.3.
What distinguishes callbacks from higher order functions in Scala?
7.4.
Are higher order functions in Scala closures?
7.5.
What is a reduced higher order function in Scala?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Higher Order Functions in Scala

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

We all had heard about the Scala programming language and its various functionalities at least once. Ever wonder what is these functions that differ Scala from other languages? 

higher order function in scala

This article will discuss higher order functions in Scala. We will talk about its definition and how higher order functions in Scala work. We will be going into detail but first, let’s see what Scala is.

Also see, Must Do Coding Questions

What is Scala

Scala stands for Scalable Language. It is a multi-paradigm programming language. It consists of the functional and object-oriented elements of programming. The source code for Scala is a statically typed language and is converted into byte code during compilation. 

Why is Scala used?

The following are the reasons why Scala is used heavily nowadays:

  • Scala code is simpler to test and reuse. 
  • Its parallelisation is streamlined, and the application as a whole contains fewer problems. 
  • With a top-down approach, Scala programming divides each programme into several pieces that may be handled in parallel, accelerating the process and enhancing efficiency.
     

Application of Scala

Some applications of Scala are listed below:

  • Scala allows parallel and batch data processing.
  • Scala is used in the front and back ends of web applications.
  • It can be used with Hadoop / Reduce/Map programs.
  • It is used in the AWS Lambda function.
  • It is used with ML at large-scale for building complex algorithms.
     

You can refer to our article, What is Scala, to better understand the Scala programming language.

Also Read About, 8085 Microprocessor Pin Diagram

Higher Order Functions in Scala

A function that accepts a function as a parameter or returns a function is called a higher order function in Scala. In contrast, if a function doesn't accept a function as an argument or return a function as output, they are known as a first-order function.

Let’s have a look at the following example,

object HigherOrderFunction extends App 
{
	  def math(n1:Int, n2:Int, fun:(Int,Int)=>Int):Int = fun(n1,n2)
	  
	  val sum = math(10,16, (n1,n2) => n1+n2)
	  val diff = math(20,14, (n1,n2) => n1-n2)

	  println(s"sum is $sum")
	  println(s"diff is $diff")
}


Output:

output for higher order function

Explanation:

In this example, we defined a math function with three parameters. The third parameter is actually a function called fun, which has two Int-type parameters and an Int-type return value. Because it anticipates a function as its third parameter, the math function, in this case, is essentially a higher order function. For this reason, we give an anonymous function (which takes two arguments) as a third argument when calling the math function.

Before going into detail about higher order functions, we will have a quick discussion about Anonymous functions, which will help you understand higher order functions in a better way.

Also Read About, YII Framework

Recommended Topic, Cognizant Eligibility Criteria

Anonymous Function

An anonymous function is a function that has no name but only a function. When you don't want to reuse a function, creating an anonymous function is a good idea. It provides a lightweight function definition.

In Scala, you can define anonymous functions by using the => or _. Look at the following example to understand the anonymous functions in a better way.

object MainObject {  
   def main(args: Array[String]) = {  
   
     // Creating an Anonymous function by using =>
     var result1 = (num1:Int, num2:Int) => num1+num2   
          
     // Creating an Anonymous function by using _
     var result2 = (_:Int)+(_:Int)   
                 
     println(result1(15,20))  
     println(result2(30,25))  
    }  
}


Output:

anonymous function

Explanation:

In the above example, we are creating two anonymous functions using two different ways. We are using the => operator to make the first anonymous function whose name is result1. The value will get processed when it is called. The _ operator is also used to make the anonymous function, result2. It will get operated once it is called.

You can also read about mock interview.

Function as Parameter

From the definition of higher order functions in scala, we know that higher order functions in scala take functions as parameters. Well, there are some ways in which these parameters are parsed. Following are some functions that take parameters and perform their transformations according to the need.

Using map

map function is a collection of key-value pairs. Keys are always unique, although values do not have to be. Any data type can be used in key-value pairs. There are two kinds of maps: mutable and immutable. Scala, by default, uses an immutable map.

Let’s look at an example,

object mapfunction
{
	def main(args:Array[String])
	{
			val mapIm = Map("Alankrit" -> 30,
							"Mohak" -> 20,
							"Nakul" -> 50)

			val alankrit = if(mapIm.contains("Alankrit"))
							mapIm("Alankrit") else 0

			val mohak = if(mapIm.contains("Mohak"))
							mapIm("Mohak") else 0
		
			val nakul = if(mapIm.contains("Nakul"))
							mapIm("Nakul") else 0

			println("Alankrit:" + alankrit)
			println("Mohak:" + mohak)
			println("Nakul:" + nakul)
	}
}


Output:

output for map function

Explanation:

As we know, the map function works on key-value pairs. In the above example, we provided keys for Alankrit, Mohak and Nakul. When we request the output for these value pairs, the program checks whether there is a key present to it or not. As there are keys to every one of them, the output is a key-value pair. If they didn’t have the key, they would be printed with a NULL value.

Using flatMap

The flatMap technique removes an item's inner grouping. This procedure produces a series. The flatMap method is a shortcut for mapping and rapidly flattening a collection. In simple terms, it divides the given string into the characters contained within it, separated by a comma.

Let’s take a look at an example of flatMap,

object flatMapmethod
{
	def main(args:Array[String])
	{
		val portal = Seq("Coding", "Ninjas")
		val result = portal.flatMap(_.toUpperCase)
		println(result)
	}
}


Output:

output for flat map function

Explanation:

In the above example, the flatMap function is applied to the stated sequence (“CODING”, “NINJAS”), thus generating the list of sequences afterwards.

Using filter

To clear a collection from an element we do not need, we use the filter function.

Let’s take an example where we need only those numbers who are lesser than 15.

object filterfunction
{
	def main(args:Array[String])
	{
		val series = List(15, 22, 13, 23)
		val result = series.filter(_ < 15)
		println(result)
	}
}


Output:

output for filter function

Explanation:

In the above example, we are given a list of numbers. As we know, the filter function filters out the collection of elements that we don’t need. The condition is set inside the filter function. Afterwards, we obtained a new sequence that only contained the desired elements after executing the higher-order function and giving the appropriate predicate.

Using reduce

Scala's reduce function is applied to the collection of data structures such as lists, sets, maps, sequences, and tuples. 

The parameter in the reduce function is a binary operator that merges all of the collection's items and returns a single value. The first two values are combined using the binary operation, which is then stored in an accumulator. The accumulator is combined with the next value in the collection to get a single value.

Let’s have a look at an example of combining some elements into a single one.

object reducefunction
{
	def main(arg:Array[String])
		{
			val seq_elements: Seq[Double] = Seq(4.5, 6.0, 2.5)
			println(s"Elements = $seq_elements")

			val sum: Double = seq_elements.reduce((num1, num2) => num1 + num2)
			println(s"Sum of elements = $sum")
		}
}


Output:

output for reduce function

Explanation:

In the above example, we find the sum of elements in a sequence using reduce function. The first two values (4.5 and 6.0) are combined using the binary operation. The sum is then stored in an accumulator (10.5). Afterwards, the accumulator's value is added to the next value(10.5 and 2.5) in the collection to get the final value (13.0).

Using fold

The reduce and fold functions are pretty similar. The only difference is that the initial value for the accumulator can be set. This implies that we can also choose the kind of object that will be returned.

Let’s look at the following example,

object foldfunction
{
    def main(arg:Array[String])
    {
        val seq_elements: Seq[Double] = Seq(4.5, 6.0, 2.5)
        println(s"Elements = $seq_elements") 
  
        val sum: Double = seq_elements.fold(0.0)((num1, num2) => num1 + num2)
        println(s"Sum of elements = $sum")
    }
}


Output:

output for fold function

Explanation:

Similar to the reduce function, the fold function uses the accumulator concept. But instead of using the binary operator, we can set the initial value of the accumulator and do the operation accordingly. In the above example, let’s suppose we initialise the accumulator's value to be 0.0. The first two numbers of the sequence are then added together and stored in the accumulator (10.5). Afterwards, the accumulator's new value is combined with the next value(2.5) in the collection, and the final value will be (13.0). 

Functions Returning Functions

From the definition of higher order functions in scala, we know that it takes functions as an input or returns another function. Now, we will discuss higher order functions in Scala, which return functions as output, not the parameters.

Have a look at the following example,

object HigherorderFunction extends App {

  def math(name: String): (Int, Int) => Int = (n1: Int, n2: Int) => {
    name match {
      case "add" => n1 + n2
      case "product" => n1 * n2
      case "divide" => n1/n2
      case "subtract" => n1 - n2
    }
  }

 	 def add: (Int, Int) => Int = math("add")
 	 def sub: (Int, Int) => Int = math("subtract")
 	 def product: (Int, Int) => Int = math("product")
 	 def div: (Int, Int) => Int = math("divide")
  
 	 println(s"Addition of two numbers: ${add(7,10)}")
 	 println(s"Subtraction of two numbers: ${sub(17,10)}")
	 println(s"Product of two numbers: ${product(7,10)}")
	 println(s"Division of two numbers: ${div(20,10)}")
}


Output:

output for returning functions from functions

Explanation:

In this example, we've constructed a math function whose return type is (Int, Int) => Int. It accepts the name of the operation as a parameter. This indicates that a function that accepts two integers and returns an integer. Afterwards, we created the functions add, subtract, product, and division and provided them with their respective functionality.

Frequently Asked Questions

What does this _* mean in Scala?

The _* operator instructs the compiler to pass a series member as a separate argument to printAll, rather than to pass them as a single parameter.

Is lambda a higher-order function?

Lambda is not a higher-order function. It is an anonymous function. It can only be a higher-order function if it takes or returns a function, which lambdas do not.

What distinguishes callbacks from higher order functions in Scala?

Callback functions (CB) and higher order functions in Scala (HoF) are very different. A function that accepts or returns another function as a value is referred to as a higher-order function (HoF). While a function that is sent to another function is known as a callback function (CB).

Are higher order functions in Scala closures?

Higher order functions in Scala are simply those that take a function as an input or return another function. In an inner scope, closures are utilised to protect the outer scope. This helps make variables appear private and prevent the global scope from becoming clogged with variables.

What is a reduced higher order function in Scala?

Scala's reduced higher order function aims to create a single value from a collection's elements using the calculations we provide.

Conclusion

In this article, we have extensively discussed higher order functions in scala. We discussed taking a function as a parameter and function returning functions. We also discussed various methods to take functions as parameters. 

If you think this blog has helped you with higher order functions in Scala, and if you want to learn more, check out our articles.

You can also refer to our guided path on the basics of java and many more on our website.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! 

If you want to test your competency in coding, check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! 

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, consider our paid courses to give your career an edge over others!

Happy Learning!

Live masterclass