0
我不確定如何在匿名函數中使用return
關鍵字(或者我應該以不同的方式解決我的問題?)。如何返回匿名函數/函數字面值?
它現在的樣子,return
實際上是指封閉函數。
()=>{
if (someMethodThatReturnsBoolean()) return true
// otherwise do stuff here
}:Boolean
我不確定如何在匿名函數中使用return
關鍵字(或者我應該以不同的方式解決我的問題?)。如何返回匿名函數/函數字面值?
它現在的樣子,return
實際上是指封閉函數。
()=>{
if (someMethodThatReturnsBoolean()) return true
// otherwise do stuff here
}:Boolean
爲什麼不呢?
() =>
someMethodThatReturnsBoolean() || {
//do stuff here that eventually returns a boolean
}
或者,如果你不喜歡產生副作用與||
運營商可以只使用純如:
() =>
if (someMethodThatReturnsBoolean())
true
else {
//do something here that returns boolean eventually
}
if
只是在Scala中表達,你應該組織代碼以類似於表情的方式儘可能避免return
。
它現在的樣子,返回實際上是指封閉函數。
這就是它應該如何。您不能使用return
從匿名功能返回。您必須重寫您的代碼以避免return
聲明,如下所示:
()=>{
if (someMethodThatReturnsBoolean()) true
else {
// otherwise do stuff here
}
}:Boolean
您幾乎肯定不想要。 Scala的'return'關鍵字_always_和_only_從頂級方法返回(在類的級別,無論該類是否被命名或者是否嵌套)。因此,函數文字中的'return'或嵌套方法很少有用。 –