如何以匿名函数/函数文字返回?

use*_*000 0 scala

我不确定如何return在匿名函数中使用关键字(或者我应该以不同的方式解决我的问题?).

它现在的方式,return实际上是指封闭功能.

()=>{
  if (someMethodThatReturnsBoolean()) return true
  // otherwise do stuff here
}:Boolean
Run Code Online (Sandbox Code Playgroud)

Mar*_*ila 5

为什么不 ?

() =>
  someMethodThatReturnsBoolean() || {
    //do stuff here that eventually returns a boolean
  }
Run Code Online (Sandbox Code Playgroud)

或者,如果您不喜欢使用||操作符生成副作用,则只需使用plain:

() =>
  if (someMethodThatReturnsBoolean())
    true
  else {
    //do something here that returns boolean eventually
  }
Run Code Online (Sandbox Code Playgroud)

if只是Scala中的一个表达式,您应该以类似表达式的方式组织代码并return尽可能避免.