代码之家  ›  专栏  ›  技术社区  ›  Jus12

Scala中“return”语句的目的是什么?

  •  30
  • Jus12  · 技术社区  · 14 年前

    有什么真正的理由提供 return Scala的声明?(除了更加“Java友好”)

    4 回复  |  直到 14 年前
        1
  •  48
  •   Dave Griffith    14 年前

    忽略嵌套函数,总是可以用不带返回的等价计算替换带返回的Scala计算。这个结果可以追溯到“结构化编程”的早期,被称为 structured program theorem ,非常聪明。

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

    实际上,您希望从嵌套函数内部返回的最常见原因是为了打破理解或资源控制块的命令。(理解命令的主体被翻译成嵌套函数,尽管它看起来就像一个语句。)

    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
    }
    
        2
  •  27
  •   Randall Schulz    14 年前

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

    当然,正如戴夫·格里菲斯所说,你可以消除 return ,这样做往往比简单地用公开的命令缩短执行时间更令人困惑 返回 .

    也要意识到 返回

        3
  •  6
  •   yerlilbilgin    9 年前

    下面是一个例子

    不退还:

     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()
                }
              }
            }
          }
      }
    

    有回报:

      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()
      }
    

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

        4
  •  2
  •   Lachlan    14 年前

    return . 但是对于函数式代码,您可能需要懒惰才能获得与命令式代码相当的性能,而命令式代码可以使用 .