Scala – High order functions

  • date 20th May, 2021 |
  • by Prwatech |
  • 0 Comments

In Scala, Higher order functions are the functions that take other functions as parameters or return a function as a result. This is because functions are first-class values in Scala. so we can say High order functions are the function for both methods and functions that can take functions as parameters or that return a function.

Use case 1

val salaries = Seq(20000, 70000, 40000)
val doubleSalary = (x: Int) => x * 2
val newSalaries = salaries.map(doubleSalary)

doubleSalary is a function which takes a single Int, x, and returns x * 2. In general, the tuple on the left of the arrow => is a parameter list and the value of the expression on the right is what gets returned. On line 3, the function doubleSalary gets applied to each element in the list of salaries.

Use case 2

val salaries = Seq(20000, 70000, 40000)
val newSalaries = salaries.map(x => x * 2)

Use case 3:

// Scala program of higher order
// function
// Creating object
object prwatech {
// Main method
    def main(arg:Array[String])
    {
      // Displays output by assigning 
        // value and calling functions
        println(apply(format, 15))
      
    }
      
    // A higher order function
    def apply(x: Double => String, y: Double) = x(y)
  
    // Defining a function for
    // the format and using a
    // method toString()
    def format[R](z: R) = "{" + z.toString() + "}"
      
}

output:

{15.0}

Quick Support

image image