gpt4 book ai didi

scala - Scala 中的非本地返回是新的吗?

转载 作者:行者123 更新时间:2023-12-03 10:59:35 25 4
gpt4 key购买 nike

一位同事刚刚向我展示了这个,我很惊讶它完全编译:

def toUpper(s: Option[String]): String = {
s.getOrElse(return "default").toUpperCase
// ^^^^^^ // a return here in the closure??
}

这甚至有效:
println(toUpper(Some("text"))) // TEXT
println(toUpper(None)) // default

我以为 return不允许从内部关闭。这从什么时候开始起作用了?这种非本地返回有什么注意事项吗?

最佳答案

语义比较简单:return会抛出 NonLocalReturnControl在封闭方法中捕获,toUpper .它看起来不像最近的功能;没有提到 returnScala change-log从 2.0 版开始

以下是 Scala 语言规范第 6.20 节中的相关描述:

Returning from a nested anonymous function is implemented by throwing and catching a scala.runtime.NonLocalReturnException. Any exception catches between the point of return and the enclosing methods might see the exception. A key comparison makes sure that these exceptions are only caught by the method instance which is terminated by the return.

If the return expression is itself part of an anonymous function, it is possible that the enclosing instance of f has already returned before the return expression is executed. In that case, the thrown scala.runtime.NonLocalReturnException will not be caught, and will propagate up the call stack.



这是一个示例,其中 NonLocalReturnControl逃脱:
var g: () => Unit = _
def f() { g = () => return }
f() // set g
g() // scala.runtime.NonLocalReturnControl$mcI$sp

关于scala - Scala 中的非本地返回是新的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6915701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com