Extracting condition value in a match/case block


#1

Hello all,

I often find myself using this pattern:

foo match  {
    case x if bar(x) > threshold => 
        val a = bar(x)
        // do something with x and a
    case x if baz(x) % 5 == 0 =>
        val b = baz(x)
        // do something with x and b
    ...
}

Meaning that I need to call twice the functions that I need to evaluate the condition.

Do you guys have a better way of doing this?

Cheers,

Pierre


#2

I’d call it before your match clause and store it in a val


#3

Thanks for your answer. It is not always convenient, eg if you are in an FSM.


#5

If you encounter that pattern a lot you could make a custom extractor for it.

class Matcher[A,B](f: A => B)(p: B => Boolean) { 
  def unapply(a: A): Option[B] = {
    val b = f(a)
    if (p(b)) Some(b) else None 
  } 
}

And then

val Bar = new Matcher(bar)(_ > threshold)
val Baz = new Matcher(baz)(_ % 5 == 0)
foo match {
  case Bar(x) => doSomething(x)
  case Baz(x) => doSomething(x)
}