Scala 中“return”语句的目的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3770989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:26:31  来源:igfitidea点击:

Purpose of "return" statement in Scala?

javascalareturn

提问by Jus12

Is there any real reason of providing the returnstatement in Scala? (aside from being more "Java-friendly")

return在 Scala中提供语句有什么真正的原因吗?(除了更加“Java 友好”)

回答by Dave Griffith

Ignoring nested functions, it is always possible to replace Scala calculations with returns with equivalent calculations without returns. This result goes back to the early days of "structured programming", and is called the structured program theorem, cleverly enough.

忽略嵌套函数,总是可以用不带返回的等效计算替换带返回的 Scala 计算。这个结果可以追溯到“结构化编程”的早期,被称为结构化程序定理,够巧妙的。

With nested functions, the situation changes. Scala allows you to place a "return" buried deep inside series of nested functions. When the return is executed, control jumps out of all of the nested functions, into the the innermost containing method, from which it returns (assuming the method is actually still executing, otherwise an exception is thrown). This sort of stack-unwinding could be done with exceptions, but can't be done via a mechanical restructuring of the computation (as is possible without nested functions).

使用嵌套函数,情况会发生变化。Scala 允许您将“返回”置于深埋在一系列嵌套函数中。当返回执行时,控制跳出所有嵌套函数,进入最里面的包含方法,从那里返回(假设该方法实际上仍在执行,否则抛出异常)。这种堆栈展开可以在例外情况下完成,但不能通过计算的机械重组来完成(如果没有嵌套函数也是可能的)。

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. (The body of an imperative for-comprehension gets translated to a nested function, even though it looks just like a statement.)

您实际上想要从嵌套函数内部返回的最常见原因是为了突破命令式 for-comprehension 或资源控制块。(命令式 for-comprehension 的主体被转换为嵌套函数,即使它看起来就像一个语句。)

for(i<- 1 to bezillion; j <- i to bezillion+6){
if(expensiveCalculation(i, j)){
   return otherExpensiveCalculation(i, j)
}

withExpensiveResource(urlForExpensiveResource){ resource =>
// do a bunch of stuff
if(done) return
//do a bunch of other stuff
if(reallyDoneThisTime) return
//final batch of stuff
}

回答by Randall Schulz

It is provided in order to accommodate those circumstances in which it is difficult or cumbersome to arrange all control flow paths to converge at the lexical end of the method.

提供它是为了适应那些难以或繁琐地安排所有控制流路径以在方法的词汇端收敛的情况。

While it is certainly true, as Dave Griffith says, that you can eliminate any use of return, it can often be more obfuscatory to do so than to simply cut execution short with an overt return.

虽然这是千真万确的,因为大卫格里菲斯说,就可以消除任何使用的return,它往往可以更多的混淆,而不是简单地切断执行中短期有明显这样做return

Be aware, too, that returnreturns from methods, not function (literals) that may be defined within a method.

return还要注意,返回的是方法,而不是方法中可能定义的函数(文字)。

回答by yerlilbilgin

Here is an example

这是一个例子

This method has lots of if-else statements to control flow, because there is no return (that is what I came with, you can use your imagination to extend it). I took this from a real life example and modified it to be a dummy code (in fact it is longer than this):

这个方法有很多if-else语句来控制流程,因为没有返回(这是我自带的,大家可以发挥想象力来扩展)。我从一个真实的例子中得到了这个并将其修改为一个虚拟代码(实际上它比这个更长):

Without Return:

不退货:

 def process(request: Request[RawBuffer]): Result = {
      if (condition1) {
        error()
      } else {
        val condition2 = doSomethingElse()
        if (!condition2) {
          error()
        } else {
          val reply = doAnotherThing()
          if (reply == null) {
            Logger.warn("Receipt is null. Send bad request")
            BadRequest("Coudln't receive receipt")
          } else {
            reply.hede = initializeHede()
            if (reply.hede.isGood) {
              success()
            } else {
              error()
            }
          }
        }
      }
  }

With Return:

有回报:

  def process(request: Request[RawBuffer]): Result = {
      if (condition1) {
        return error()
      }

      val condition2 = doSomethingElse()
      if (!condition2) {
        return error()
      }

      val reply = doAnotherThing()

      if (reply == null) {
        Logger.warn("Receipt is null. Send bad request")
        return BadRequest("Coudln't receive receipt")
      }

      reply.hede = initializeHede()
      if (reply.hede.isGood)
        return success()

      return error()
  }

To my eyes, the second one is more readable and even manageable than the first one. The depth of indentation (with well formatted code) goes deep and deep if you don't use a return statement. And I don't like it :)

在我看来,第二个比第一个更具可读性,甚至更易于管理。如果不使用 return 语句,缩进的深度(使用格式良好的代码)会越来越深。我不喜欢它:)

回答by Lachlan

I view returnas a useful when writing imperative style code, which generally means I/O code. If you're doing pure functional code, you don't need (and should not use) return. But with functional code you may need laziness to get performance equivalent to imperative code that can "escape early" using return.

我认为return在编写命令式风格代码时很有用,这通常意味着 I/O 代码。如果您正在编写纯函数式代码,则不需要(也不应该使用)return. 但是对于函数式代码,您可能需要懒惰才能获得与使用return.