“返回”的目的Scala中的陈述? [英] Purpose of "return" statement in Scala?

查看:118
本文介绍了“返回”的目的Scala中的陈述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中提供 return 语句是否有任何真正的原因? (除了更加Java友好)

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

推荐答案

忽略嵌套函数,总是可以用返回替换Scala计算没有回报的等效计算。这个结果可以追溯到结构化编程的早期阶段,被称为结构化程序定理,非常巧妙。

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).

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

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

这篇关于“返回”的目的Scala中的陈述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆