bistros
bistros

Reputation: 1179

println with anonymous function not printing expected value

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?

Upvotes: 2

Views: 520

Answers (2)

Mik378
Mik378

Reputation: 22191

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

Upvotes: 3

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

Upvotes: 2

Related Questions