如何将以下var Scala代码转换为val?

时间:2011-07-24 10:02:02

标签: scala

var exit: String = expensiveOperation
if (exit.contains(...)) exit = somethingElse

关键是我只想打电话

expensiveOperation

因为它消耗了许多时钟周期

3 个答案:

答案 0 :(得分:9)

如果您不想公开其他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
}

答案 1 :(得分:8)

一个愚蠢的解决方案:只是引入另一个val。

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

答案 2 :(得分:0)

一种可能的解决方案:提取方法。

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

val exit = exitValue(...)