I'd like to have a Scala functions that returns the reference to another function, is that possible?
In Java and Scala, certain builtin (a/k/a primitive) types get passed-by-value (e.g. int or Int) automatically, and every user defined type is passed-by-reference (i.e. must manually copy them to pass only their value).
You can return multiple values by using tuple. Function does not return multiple values but you can do this with the help of tuple.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With