1

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

尽管如此,我还是找到了这种方法,但这确实感觉像是在作弊

我正在解析一个查询,我发现找到一个字段!值,我想将它翻译成字段:<>值,然后继续处理,所以我提出了这段代码以避免可变,或者至少有他们被禁锢...

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)
}

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

4

3 回答 3

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)
}
于 2012-09-08T21:05:51.323 回答
3

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

val operator = ConditionOperator.toConditionOperator(parsedOperator)
val negated = parsedNegated == "!"
if (!negated || operator != ConditionOperator.Unknown) (operator, negated)
else (ConditionOperator.NotEqual, false)
于 2012-09-08T21:06:07.083 回答
1

那么你可以通过取negated出来简化逻辑。然后,模式匹配比你以前的更干净。

val negated = parsedNegated == "!"
val operator = ConditionOperator.toConditionOperator(parsedOperator) match {
  case op if negated && op == ConditionOperator.Unknown => ConditionOperator.NotEqual
  case op => op
}
于 2012-09-08T21:29:35.593 回答