Scala 如何返回匿名函数/函数文本?

Scala 如何返回匿名函数/函数文本?,scala,Scala,我不知道如何在匿名函数中使用return关键字(或者我应该用另一种方式解决我的问题?) 按照现在的方式,返回实际上是指封闭函数 ()=>{ if (someMethodThatReturnsBoolean()) return true // otherwise do stuff here }:Boolean 为什么不呢 () => someMethodThatReturnsBoolean() || { //do stuff here that eventuall

我不知道如何在匿名函数中使用
return
关键字(或者我应该用另一种方式解决我的问题?)

按照现在的方式,
返回实际上是指封闭函数

()=>{
  if (someMethodThatReturnsBoolean()) return true
  // otherwise do stuff here
}:Boolean
为什么不呢

() =>
  someMethodThatReturnsBoolean() || {
    //do stuff here that eventually returns a boolean
  }
或者,如果您不喜欢使用
|
操作符产生副作用,您可以在以下情况下使用plain:

() =>
  if (someMethodThatReturnsBoolean())
    true
  else {
    //do something here that returns boolean eventually
  }
如果
只是Scala中的一个表达式,您应该以类似表达式的方式组织代码,并尽可能避免
返回

按照现在的方式,返回实际上是指封闭函数

()=>{
  if (someMethodThatReturnsBoolean()) return true
  // otherwise do stuff here
}:Boolean
应该是这样的。不能使用
return
从匿名函数返回。您必须重写代码以避免出现
return
语句,如下所示:

()=>{
  if (someMethodThatReturnsBoolean()) true
  else {
    // otherwise do stuff here
  }
}:Boolean

你几乎肯定不想。Scala的
return
关键字始终且仅从顶级方法返回(在类级别,无论该类是否命名或是否嵌套)。因此,函数文本或嵌套方法中的
return
很少有用。