Value =?
def value:int = {def one (x:int): Int = {return x; 1} val = (x:int) = {return x; 2} 1 + one (2) + TW O (3)} println (value)
Explain
It's complicated.
Explanation
Scala does not complain about unreachable code, therefore the code compiles fine. If you want to is warned about unreachable code and then use the compiler Option-ywarn-dead-code. If you want to see a compiler error instead of a warning, then in addition use the compiler option-xfatal-warnings.
The answer to this question can is found in sls§6.20:
A return expression Return E must occur inside the body of some enclosing named method or function. The innermost enclosing named method or function in a source program, F, must has an explicitly declared result type, and The type of E must conform to it. The return expression evaluates the expression E and returns its value as the result of F. The evaluation of any statements or expressions following the return expression is omitted.
For the first return x statement the enclosing named method was method one, but for the second return x statement the Enclo Sing named method is method value. When the function (3) was called as part of the expression 1 + one (2) + A (3), then the result 3 is returned as the Res Ult of method value.
BTW, returning from a nested anonymous function was implemented by throwing and catching a scala.runtime.NonLocalReturnCont Rol.
The most common reason your actually would want to return from inside a nested function was to break out of a imperative fo R-comprehension or resource control block. See the answers to the Stack Overflow question Purpose of ' return ' statement in Scala? For a further discussion of that aspect
The return statement for Scala can be consulted:
http://stackoverflow.com/questions/3770989/purpose-of-return-statement-in-scala/3771243#3771243
Scala Fun question-return statement