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)
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)
}
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 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)