I'd like to have a Scala functions that returns the reference to another function, is that possible?
You can return a function type (this is defined by A => B
). In this case Int to Int:
scala> def f(x:Int): Int => Int = { n:Int => x + n }
f: (x: Int)(Int) => Int
When you call the function you get a new function.
scala> f(2)
res1: (Int) => Int = <function1>
Which can be called as a normal function:
scala> res1(3)
res2: Int = 5
One way (somewhat unique to functional object-orientation) you can use higher order functions is to create loose couplings between objects.
In the example below the class Alarm
has a method check4Danger()
that checks if a calculated value exceeds the DangerLevel
. The Alarm class does not know anything about the objects that call it.
The Car
class has a method engineCrashRisk()
that returns an anonymous function that calculate the risk of engine crash. Car
does not have dependency to Alarm.
case class Alarm(temperature: Double, pressure: Double){
val DangerLevel = 100000.0
def check4Danger( f: (Double, Double) => Double): Boolean = {
val risk = f(temperature, pressure)
if( risk > DangerLevel ){
println("DANGER: "+ risk )
true
}else{
println("Safe: " + risk)
false
}
}
}
case class Car(fuelRate: Double, milage: Int){
def engineCrashRisk() =
(temperature: Double, pressure: Double) =>
temperature * milage + 2*pressure / fuelRate
}
val car = Car(0.29, 123)
val riskFunc = car.engineCrashRisk
val alarm = Alarm(124, 243)
val risk = alarm.check4Danger(riskFunc)
The output of this script is:
Safe: 16927.862068965518
In this example we used anonymous functions with closures to create a dependency free method call between the Alarm
and Car
objects. Does this example make any sense?