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
returnstatement returns from the enclosing method body. Ifreturnappears inside of a function literal, it is implemented with exception throwing.returnwill 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:The
returnin this example returns from thegeometricAveragemethod, allowing it to complete instantly if a 0 is found. You don't need to know thatfoldLeftis 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
returnunnecessary. For example:If you really want to use
returnin the definition of the function, you can implement the appropriate function interface manually instead of using a function literal:But this is not idiomatic and strongly discouraged.