Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is non-local return in Scala new?

A colleague just showed me this and I was surprised that it compiled at all:

def toUpper(s: Option[String]): String = {
  s.getOrElse(return "default").toUpperCase
  //          ^^^^^^  // a return here in the closure??
}

and this even works:

println(toUpper(Some("text"))) // TEXT
println(toUpper(None))         // default

I thought return from inside a closure was not allowed. Since when has this worked? Are there caveats with such non-local returns?

like image 877
Jean-Philippe Pellet Avatar asked Aug 02 '11 16:08

Jean-Philippe Pellet


2 Answers

The semantics are relatively simple: return will throw a NonLocalReturnControl that is caught at the enclosing method, toUpper. It doesn't look like a recent feature; there is no mention of return in the Scala change-log since version 2.0.

Here's the relevant description from the Scala Language Spec, section 6.20:

Returning from a nested anonymous function is implemented by throwing and catching a scala.runtime.NonLocalReturnException. Any exception catches between the point of return and the enclosing methods might see the exception. A key comparison makes sure that these exceptions are only caught by the method instance which is terminated by the return.

If the return expression is itself part of an anonymous function, it is possible that the enclosing instance of f has already returned before the return expression is executed. In that case, the thrown scala.runtime.NonLocalReturnException will not be caught, and will propagate up the call stack.

Here's an example in which the NonLocalReturnControl escapes:

var g: () => Unit = _ def f() { g = () => return } f() // set g g() // scala.runtime.NonLocalReturnControl$mcI$sp 
like image 170
Kipton Barros Avatar answered Sep 20 '22 17:09

Kipton Barros


It's been allowed since forever, more or less. It might look strange there, but there are many places where the reverse would be true. For example:

// excessive use of braces for the sake of making scopes clearer  def findFirst[A](l: List[A])(p: A => Boolean): Option[A] = {     for (x <- l) {         if (p(x)) return Some(x)     }     None } 
like image 38
Daniel C. Sobral Avatar answered Sep 20 '22 17:09

Daniel C. Sobral