Scala 趣题 16 return 语句

value = ?


  def value: Int = {
    def one(x: Int): Int = { return x; 1}
    val two = (x: Int) => { return x; 2 }
    1 + one(2) + two(3)
  }
  
  println(value)

























解释

有点复杂


Explanation


Scala does not complain about unreachable code, therefore the code compiles fine. If you want to be warned about unreachable code, 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 be 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 have 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 is method one, but for the second return x statement the enclosing named method is method value. When the function two(3) is called as part of the expression 1 + one(2) + two(3), then the result 3 is returned as the result of method value.


Btw, returning from a nested anonymous function is implemented by throwing and catching a scala.runtime.NonLocalReturnControl.


The most common reason you actually would want to return from inside a nested function is to break out of an imperative for-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


关于scala的return语句可以参考:

http://stackoverflow.com/questions/3770989/purpose-of-return-statement-in-scala/3771243#3771243

你可能感兴趣的:(scala)