2011-07-24 51 views

回答

8

如果你不想暴露其他val,做內聯:

val exit = { 
    val result = expensiveOperation 
    if (result.contains(...)) somethingElse 
    else result 
} 

,或者,如果你喜歡

val exit = expensiveOperation match { 
    case res if res.contains(...) => somethingElse 
    case res if res.contains(...) => somethingBetter 
    // ... 
    case res => res 
} 
8

一個愚蠢的解決方案:只引入另一VAL。

val expected = expensiveOperation 
    val exit = if(expected.contains(...)) expected else something else 
+7

不能看到什麼是愚蠢的有關 –

0

一個可能的解決方案:提取一種方法。

def exitValue(...): String = { 
    val exit: String = expensiveOperation 
    if (exit.contains(...)) somethingElse else exit 
} 

val exit = exitValue(...) 
+0

你可以在沒有額外方法的情況下直接寫入。 – Debilski