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

Scala在匿名函数中返回语句

发布时间:2020-12-16 09:41:03 所属栏目:安全 来源:网络整理
导读:为什么匿名函数中的显式返回语句(一个使用return关键字)从封闭的命名函数返回,而不仅仅是从匿名函数本身返回? 例如。以下程序会导致类型错误: def foo: String = { ((x: Integer) = return x) "foo"} 我知道建议避免使用return关键字,但是我有兴趣为什么
为什么匿名函数中的显式返回语句(一个使用return关键字)从封闭的命名函数返回,而不仅仅是从匿名函数本身返回?

例如。以下程序会导致类型错误:

def foo: String = {
  ((x: Integer) => return x)
  "foo"
}

我知道建议避免使用return关键字,但是我有兴趣为什么显式和隐式返回语句在匿名函数中具有不同的语义。

在下面的例子中,在m执行结束后,return语句“存活”,程序导致运行时异常。如果匿名函数没有从封闭函数返回,则无法编译该代码。

def main(args: Array[String]) {
  m(3)
}

def m: (Integer => Unit) =
  (x: Integer) => return (y: Integer) => 2

解决方法

正式地,return定义为始终从最近的封闭命名方法返回

A return expression return e must occur inside the body of some
enclosing named method or function. The innermost enclosing named
method or function in a source program,f,must have an explicitly
declared result type,and the type of e must conform to it. The return
expression evaluates the expression e and returns its value as the
result of f . The evaluation of any statements or expressions
following the return expression is omitted.

所以在lambda中没有不同的语义。皱纹是,与普通方法不同,从lambda创建的闭包可以转义对封闭方法的调用,如果在这样的闭包中有返回,则可以获取异常。

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

现在,为“为什么”。一个较小的原因是美学:lambdas是表达式,当表达式及其所有子表达式具有相同的含义,无论嵌套结构如何,它都很好。 Neal Gafter在http://gafter.blogspot.com/2006/08/tennents-correspondence-principle-and.html谈到

然而,它存在的主要原因是它允许您轻松模拟命令式编程中常用的控制流形式,但仍允许您将事物抽象为更高级的功能。作为玩具示例,Java的foreach构造(“for x:xs {yada;}”)允许在循环内返回。 Scala没有语言水平foreach。相反,它在图书馆(不计算“表达”没有收益,因为他们只是desugar foreach)foreach)。具有非本地返回意味着您可以使用Java foreach并直接转换为Scala foreach。

BTW,Ruby,Smalltalk和Common Lisp(我的头顶)也有类似的“非本地”返回。

(编辑:李大同)

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

    推荐文章
      热点阅读