quite often I have code like the following
if (operator == Equal || operator == Missing || operator == Unknown) {
To make it less verbose and a little bit more readable sometimes I issue:
if (List(Equal, Missing, Unknown).contains(operator)) {
I know I could also issue pattern matching, like this
operator match {
case Equal | Missing | Unknown => {
which brings another level of nesting braces
I was wondering if there's some kind of method like
if (operator.isOneOf(List(Equal, Missing, Unknown))) {
--
edit:
to show how to use the different options that appeared here:
Using Set as a function
if (Set(1, 2, 3)(3)) {
"Gotcha"
} else {
"no luck..."
}
Using PartialFunction.cond
import PartialFunction.cond
if (cond(3) { case 1 | 2 | 3 => true }) {
"Gotcha"
} else {
"no luck..."
}
Implementing isOneOf
class ComparableWithIsOneOf[T](val value: T) {
def isOneOf(values: T*): Boolean = {
values.contains(value)
}
}
object Comparison {
object implicits {
implicit def AnyToComparableWithIsOneOf[T](value: T): ComparableWithIsOneOf[T] = {
return new ComparableWithIsOneOf(value)
}
}
}
import Comparison.implicits._
if (3.isOneOf(1, 2, 3)) {
"Gotcha"
} else {
"no luck..."
}
In the end I like the Set() version better, but I think the best is to stick with pattern matching, is more standard and idiomatic...