带有匿名函数的 println 不打印预期值 [英] println with anonymous function not printing expected value

查看:65
本文介绍了带有匿名函数的 println 不打印预期值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 Scala 匿名函数.

I wonder about Scala anonymous functions.

object hello { 
  def main(args: Array[String]) { 
    println ( ( (x:Int)=>return x+1)(1) ) 
  } 
}

我预计结果为2",但输出为空白.我的假设错了吗?

I expected the result to be '2' but the output is blank. Was my assumption wrong?

推荐答案

lambda 的结果是 lambda 主体中最后一条语句的结果,因此您可以添加结果值(在这种情况下是字面量 ())作为最后一条线.

The result of lambda is the result of the last statement in lambda body, so you could just add result value (in this case literal ()) as the last line.

lambda 中的 return 将使用异常 (NonLocalReturnControl) 从周围的方法返回,而不是从 lambda 本身返回.

return in lambda will return from the surrounding method rather than from the lambda itself using exception (NonLocalReturnControl).

在您的情况下,您的退货将返回一个单位.

In your case your return will return a Unit.

有效代码如下:

println ( ( (x:Int)=> x+1)(1) )

这篇关于带有匿名函数的 println 不打印预期值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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