2013-04-15 60 views
0

我不確定如何在匿名函數中使用return關鍵字(或者我應該以不同的方式解決我的問題?)。如何返回匿名函數/函數字面值?

它現在的樣子,return實際上是指封閉函數。

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

您幾乎肯定不想要。 Scala的'return'關鍵字_always_和_only_從頂級方法返回(在類的級別,無論該類是否被命名或者是否嵌套)。因此,函數文字中的'return'或嵌套方法很少有用。 –

回答

5

爲什麼不呢?

() => 
    someMethodThatReturnsBoolean() || { 
    //do stuff here that eventually returns a boolean 
    } 

或者,如果你不喜歡產生副作用與||運營商可以只使用純如:

() => 
    if (someMethodThatReturnsBoolean()) 
    true 
    else { 
    //do something here that returns boolean eventually 
    } 

if只是在Scala中表達,你應該組織代碼以類似於表情的方式儘可能避免return

4

它現在的樣子,返回實際上是指封閉函數。

這就是它應該如何。您不能使用return從匿名功能返回。您必須重寫您的代碼以避免return聲明,如下所示:

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