Reputation: 63415
I'm trying to avoid mutable variables as much as possible, but sometimes it just feels too hard, and I don't want to end with an extremely complicated code
Nevertheless I found this way to do it, but it certainly feels like cheating
I'm parsing a query, and I find find a field!value, I want to translate it to field:<>value, and then go on processing, so I came out with this code to avoid mutables, or at least to have them confined...
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)
}
Is this the right way to do it??? or is there a more idiomatic (and clear!) way to achieve this kind of things?
Upvotes: 1
Views: 1713
Reputation: 51109
Well you can simplify the logic by taking negated
out. Then, pattern matching is cleaner than what you had before.
val negated = parsedNegated == "!"
val operator = ConditionOperator.toConditionOperator(parsedOperator) match {
case op if negated && op == ConditionOperator.Unknown => ConditionOperator.NotEqual
case op => op
}
Upvotes: 1
Reputation: 52681
This is indeed cheating since var
is mutable!
The way to correct this is to simply return the if-statement's result directly:
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)
}
Upvotes: 6
Reputation: 167891
The typical way to do it would be without the temporary vars either, since you don't really need them.
val operator = ConditionOperator.toConditionOperator(parsedOperator)
val negated = parsedNegated == "!"
if (!negated || operator != ConditionOperator.Unknown) (operator, negated)
else (ConditionOperator.NotEqual, false)
Upvotes: 3