Purpose of quot;returnquot; statement in Scala?(“退货的目的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 允许您在一系列嵌套函数中放置一个返回".执行 return 时,控制跳出所有嵌套函数,进入最里面的包含方法,并从中返回(假设该方法实际上仍在执行,否则将引发异常).这种堆栈展开可以在例外情况下完成,但不能通过计算的机械重组来完成(在没有嵌套函数的情况下是可能的).
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).
您实际上希望从嵌套函数内部返回的最常见原因是跳出命令式的理解或资源控制块.(命令式 for-comprehension 的主体被转换为嵌套函数,即使它看起来就像一个语句.)
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 中的声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“退货"的目的Scala 中的声明?
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01