Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: return reference to a function

Tags:

scala

I'd like to have a Scala functions that returns the reference to another function, is that possible?

like image 216
mariosangiorgio Avatar asked Jul 29 '10 14:07

mariosangiorgio


People also ask

Does Scala pass by reference?

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).

How do I return multiple values from a function in Scala?

You can return multiple values by using tuple. Function does not return multiple values but you can do this with the help of tuple.


2 Answers

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
like image 108
Thomas Avatar answered Sep 28 '22 20:09

Thomas


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?

like image 25
olle kullberg Avatar answered Sep 28 '22 21:09

olle kullberg