2

I wonder about Scala anonymous functions.

object hello { 
  def main(args: Array[String]) { 
    println ( ( (x:Int)=>return x+1)(1) ) 
  } 
}

I expected the result to be '2' but the output is blank. Was my assumption wrong?

Cœur
  • 37,241
  • 25
  • 195
  • 267
bistros
  • 1,139
  • 1
  • 9
  • 23

2 Answers2

3

I don't get a blank as you evoked result but the following compiler error:

scala> println ( ( (x:Int)=> return x+1)(1) )
<console>:8: error: return outside method definition
              println ( ( (x:Int)=> return x+1)(1) )

Remove the return keyword, often useless in Scala besides:

scala> println ( ( (x:Int)=>x+1)(1) )
2

Indeed, return only ever returns from a method (defined with def).
Your function literal call is not wrapped into a method body, that's why you have this error.

To illustrate, this code snippet would be valid:

scala> def wrappingMethod(): Int = {  //note this enclosing method
  ((x:Int)=> return x+1)(1)           // it's valid to call return here
}
     |      | wrappingMethod: ()Int

scala> wrappingMethod()
res3: Int = 2
Mik378
  • 21,881
  • 15
  • 82
  • 180
  • I'm sorry My Run Envornment isn't REPL I did on idea13 object hello { def main(args: Array[String]) { println ( ( (x:Int)=>return x+1)(1) ) } } thank you – bistros Jun 16 '14 at 10:48
  • @bistros This also returns a compiler error, using IDEA 13 too: `scala> object hello { def main(args: Array[String]) { println ( ( (x:Int)=>return x+1)(1) ) } } :7: warning: enclosing method main has result type Unit: return value discarded object hello { def main(args: Array[String]) { println ( ( (x:Int)=>return x+1)(1) ) } }` – Mik378 Jun 16 '14 at 11:10
2

The result of lambda is the result of the last statement in lambda body, so you could just add result value (in this case literal ()) as the last line.

return in lambda will return from the surrounding method rather than from the lambda itself using exception (NonLocalReturnControl).

In your case your return will return a Unit.

The valid code looks like:

println ( ( (x:Int)=> x+1)(1) )