var exit: String = expensiveOperation
if (exit.contains(...)) exit = somethingElse
最關鍵的是我只希望調用如何將以下var Scala代碼轉換爲vals?
expensiveOperation
一次,因爲它消耗的時鐘週期數
var exit: String = expensiveOperation
if (exit.contains(...)) exit = somethingElse
最關鍵的是我只希望調用如何將以下var Scala代碼轉換爲vals?
expensiveOperation
一次,因爲它消耗的時鐘週期數
如果你不想暴露其他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
}
一個愚蠢的解決方案:只引入另一VAL。
val expected = expensiveOperation
val exit = if(expected.contains(...)) expected else something else
一個可能的解決方案:提取一種方法。
def exitValue(...): String = {
val exit: String = expensiveOperation
if (exit.contains(...)) somethingElse else exit
}
val exit = exitValue(...)
你可以在沒有額外方法的情況下直接寫入。 – Debilski
不能看到什麼是愚蠢的有關 –