TOUR OF SCALA
HIGHER-ORDER FUNCTIONS

Updated:01/20/2023 by Computer Hope

Methods and functions usually express behaviours or data transformations, therefore having functions that compose based on other functions can help building generic mechanisms.
For those who know Java 8+, it’s probably not an unfamiliar subject.
To conclude, Scala library.
One of the most common examples is the higher-order function map which is available for collections in Scala.

   
val Mysalaries = Seq( 70000, 20000,40000)
val doubleSalary = (x: Int) => x * 2
val newMySalaries = salaries.map(doubleSalary) // List(140000,40000, 80000)
Let’s begin by doing some of Scala’s most popular higher-order functions. And each one takes a function as a parameter.

Below is an example of a scala higher order function

 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 of the three methods vary only by the multiplication factor. To simplify, you can extract the repeated code into a higher-order function like so:
  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)     
 }


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

//here  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

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

Features of Higher order function in scala

  • reusable code
  • It is way to abstract the code in higher level
  • It is provide flexibility in code.
  • it takes one or more functions as parameters
  • it is return a function