All* function evaluations of the form
f({code})
are equivalent to
val temp = { code }
f(temp)
So, in the first case,
val temp = return "1"
None.foreach(temp) // Never reach this point!
While in the second,
val temp = (x: Nothing) => return 1
// Equivalent: new Function1[Nothing,String]{ def apply(x: Nothing) = return "1" }
None.foreach(temp) // Never call that weird function!
so everything is okay.
But, wait, foreach
takes an A => Unit
. How is return "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 from Nothing
. So, indeed, Nothing
is a subclass of Function1[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.