My colleagues and I are a bit stumped over the following code’s behavior.
def a: String = {
None.foreach(return "1")
return "2"
}
def b: String = {
None.foreach(x => return "1")
return "2"
}
As expected, invoking b does return “2”. However, invoking a returns “1”. When exactly is return "1" being evaluated when a is executed?
All* function evaluations of the form
are equivalent to
So, in the first case,
While in the second,
so everything is okay.
But, wait,
foreachtakes anA => Unit. How isreturn "1"such a function? Well, Scala starts with the most specific type possible (Nothing, which is a subclass of anything, and therefore promises to do anything you ask of it, except it can’t exist). And, then, since no values is produced by the statement (control escapes via a return), it never modifies it fromNothing. So, indeed,Nothingis a subclass ofFunction1[A,Unit].And to produce that
Nothing–well, to pretend to produce it–you actually run the code, and return.* Actually, if the parameter is passed by name, it’s secretly converted to
() => { Code }and passed in without evaluation.