试图避免scala中的mutable ..这是正确的方法吗?

时间:2012-09-08 20:57:43

标签: scala variables immutability

我试图尽可能地避免变量变量,但有时它感觉太难了,我不想以极其复杂的代码结束

尽管如此,我发现这样做的方式,但肯定会感觉像是作弊

我正在解析一个查询,我发现找到一个字段!值,我想把它翻译成字段:<> value,然后继续处理,所以我出来了这段代码以避免变异,或者至少让他们受限......

val (operator, negated) = {
  var operator = ConditionOperator.toConditionOperator(parsedOperator)
  var negated = parsedNegated == "!"
  // field!value => field notEqual value
  if (negated && operator == ConditionOperator.Unknown) {
    negated = false
    operator = ConditionOperator.NotEqual
  }
  (operator, negated)
}

这是正确的方法吗?还是有一种更惯用(和清晰!)的方式来实现这种事情?

3 个答案:

答案 0 :(得分:6)

这确实是作弊,因为var是可变的!

纠正这种情况的方法是直接返回if语句的结果:

val (operator, negated) = {
  val operator = ConditionOperator.toConditionOperator(parsedOperator)
  val negated = parsedNegated == "!"
  // field!value => field notEqual value
  if (negated && operator == ConditionOperator.Unknown)
    (ConditionOperator.NotEqual, false)
  else
    (operator, negated)
}

答案 1 :(得分:3)

这样做的典型方法是没有临时变量,因为你真的不需要它们。

val operator = ConditionOperator.toConditionOperator(parsedOperator)
val negated = parsedNegated == "!"
if (!negated || operator != ConditionOperator.Unknown) (operator, negated)
else (ConditionOperator.NotEqual, false)

答案 2 :(得分:1)

你可以通过negated来简化逻辑。然后,模式匹配比以前更清晰。

val negated = parsedNegated == "!"
val operator = ConditionOperator.toConditionOperator(parsedOperator) match {
  case op if negated && op == ConditionOperator.Unknown => ConditionOperator.NotEqual
  case op => op
}