Scala Reactive Programming
上QQ阅读APP看书,第一时间看更新

Higher-Order Functions

In Scala, Higher-Order Functions (HOF) are functions that should have one or more of the following things:

  • It should have one or more function(s) as its parameters
  • It should return a function as its result

Let us explore a HOF which takes a function as a parameter, using Scala REPL function as a function parameter:

scala> val addOne = (x: Int) => x + 1 
addOne: Int => Int = <function1> 
 
scala> def hof(f: Int => Int) = f 
hof: (f: Int => Int)Int => Int 
 
scala> val result = hof(addOne) 
result: Int => Int = <function1> 
 
scala> result(10) 
res14: Int = 11 

Here, we are passing the addOne() function to the hof() function as a parameter.

We can observe these kind of functions a lot in Scala, Akka Toolkit, and Play Framework source code, for instance, the map() and flatMap() functions.

Let us explore a HOF which has a function as its result type, using Scala REPL:

scala> def fun(a:Int, b:Int): Int => Int = a => b 
fun: (a: Int, b: Int)Int => Int 
 
scala> fun(10,20) 
res15: Int => Int = <function1> 
 
scala> res15(30) 
res17: Int = 20 
 
scala> res15(1) 
res18: Int = 20 

Here, we are returning a function of type Int => Int from another function. So, that is also an example of a HOF.