I'm trying to do something like this:
var fun : (Int,Int) => Double = (a,b) =>
{
// do something
return 1.0
}
However, my IDE complaints with Return statement outside method definition
. So how do I explicitly give a return statement in a function literal in scala?
In Scala a return
statement returns from the enclosing method body. If return
appears inside of a function literal, it is implemented with exception throwing. return
will throw an exception inside of the function which will then be caught be the enclosing method. Scala works this way in order to make the use of custom control constructs that take functions invisible, for example:
def geometricAverage(l: List[Double]): Double = {
val product = l.foldLeft(1.0) { (z, x) =>
if (x == 0) return 0 else z * x
}
Math.pow(product, 1.0 / l.length)
}
The return
in this example returns from the geometricAverage
method, allowing it to complete instantly if a 0 is found. You don't need to know that foldLeft
is a method that takes a function rather than a built-in construct to realize this.
The preference in Scala is to write functions in functional style, taking advantage of Scala's expression-oriented nature to make return
unnecessary. For example:
val fun: (Int,Int) => Double = (a,b) => {
if (a == b) {
// side effect here, if desired
0.0
} else {
// side effect here, if desired
1.0
}
}
If you really want to use return
in the definition of the function, you can implement the appropriate function interface manually instead of using a function literal:
val fun = new Function2[Int, Int, Double] {
def apply(x: Int, y: Int): Double = {
if (x == y)
return 0.0
1.0
}
}
But this is not idiomatic and strongly discouraged.