加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala中的非本地回报是否新增?

发布时间:2020-12-16 09:45:42 所属栏目:安全 来源:网络整理
导读:一个同事刚刚向我展示了这一点,我很惊讶,它编译完全是: def toUpper(s: Option[String]): String = { s.getOrElse(return "default").toUpperCase // ^^^^^^ // a return here in the closure??} 这甚至起作用: println(toUpper(Some("text"))) // TEXTp
一个同事刚刚向我展示了这一点,我很惊讶,它编译完全是:

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将抛出一个NonLocalReturnControl,该对象被封闭的方法toUpper捕获。它看起来不像最近的一个功能;自2.0版以来, Scala change-log没有回报。

以下是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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读