return
or return expr
is of type Nothing
. You can replace this for any type, since it never gives a value to the surrounding expression, instead it returns control to the caller.
In your program, it is masked as the required type () => Unit
.
Here is sometimes a convenient use for this (although you can be tarnished as uniomatic, if you use it too often, do not tell anyone who heard it from me!)
def foo(a: Option[Int]): Int = { val aa: Int = a.getOrElse(return 0) aa * 2 }
For the record, you should probably write:
def foo(a: Option[Int]): Int = a.map(_ * 2).getOrElse(0)
You can get a sense of the compiler's mind by checking the output of scala -Xprint:typer -e <one-liner>
. Add -Ytyper-debug
if you like to sift through -Ytyper-debug
channels!
scala210 -Ytyper-debug -Xprint:typer -e 'def foo: Any = {val x: () => Any = { return }}' ... elided ... typed return (): Nothing adapted return (): Nothing to () => Any,
source share