Higher-order functions take other functions as parameters or return another function due to some computation. They are helpful in function composition, where some results are calculated using more than one function.
object HigherOrderFunction{ def main(args: Array[String]){ println(perform(style,45)) } def perform(x: Int => String, y: Int) = x(y) val style = (x: Int) => "{ " + x.toString() + " }" }
The perform
function in line 5
takes the function x
as an input and applies it to the value y
. The function x
takes an integer as a parameter and styles the input as a string shown in the output.
Next, we will see how we can add two numbers in different ways using some higher-order functions:
object HigherOrderFunction{ def main(args: Array[String]){ println("Normal sum is: " + addition(plainSum,2,3)) println("Squared sum is: " + addition(squareSum,2,3)) println("Cubed sum is: " + addition(cubeSum,2,3)) } //This function takes a higher-order function as an argument, which, in turn, takes two integers as an input and returns an integer. def addition(f: (Int, Int) => Int,a: Int, b:Int): Int = f(a,b) val plainSum = (x: Int, y: Int) => (x + y) val squareSum = (x: Int, y: Int) => (x*x + y*y) val cubeSum = (x: Int, y: Int) => (x*x*x + y*y*y) }
The warning is generated to inform that the features we are using in code might get removed or discontinued in the future as there are newer features available.
The addition
function in line 9
takes a function f
as an input and applies its other two inputs, a
and b
, on f
as f(a,b)
.
In the example above, the function f
is defined by three functions that perform addition on the normal, squared, and cubed integers provided to it as inputs.
RELATED TAGS
CONTRIBUTOR
View all Courses