Alex Rivera | Logout

Scala return statements in anonymous functions

Asked 2013-07-19T20:30:59.080
35

Why does an explicit return statement (one that uses the return keyword) in an anonymous function return from the enclosing named function, and not just from the anonymous function itself?

E.g. the following program results in a type error:

def foo: String = {
  ((x: Integer) => return x)
  "foo"
}

I know it's recommended to avoid the return keyword, but I'm interested in why the explicit and implicit return statements have a different semantics in anonymous functions.

In the following example, the return statement "survives" after m has finished executing, and the program results in a run-time exception. If anonymous functions didn't return from the enclosing function, it would not be possible to compile that code.

def main(args: Array[String]) {
  m(3)
}

def m: (Integer => Unit) =
  (x: Integer) => return (y: Integer) => 2
Edit
Report

1 Answer

4

The return keyword is reserved for (class) methods, it cannot be used in functions. You can easily test that:

object Foo {
  val bar = (i: Int) => return i + i
}

This gives

<console>:42: error: return outside method definition
       object Foo { val bar = (i: Int) => return i + i }
                                          ^

Mostly you can treat methods and functions as the same, because of the function's apply method behaving syntactically like calling a method, and so-called eta-expansion allowing a method to be passed as a function argument.

In this case, it makes a difference. When defining as method, it is legal:

object Foo { 
  def bar(i: Int): Int = return i + i
}

In summary, you should only use return in methods that allow conditional (early) returns. See this post for a discussion on methods versus functions.

answered 2013-07-19T20:49:12.247

Your Answer