Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

re-use a guard in Scala

Tags:

scala

I often find myself wanting to reuse the result of a guard evaluation in scala, e.g.

blah match {
  case Blah(a, b) if expensive(a) < 10 =>
     expensive(a)
  case _ => b
}

Is this possible using some lesser-known incantation? (putting an @ on the expensive doesn't work)

Will this be possible anytime soon?

like image 339
fommil Avatar asked Sep 02 '13 16:09

fommil


1 Answers

You can do something similar using a custom extractor. This should work:

case class Blah(a: Int, b: Int)

object expensive {
  def unapply(x: Int): Option[Double] = Some(math.cos(x))
}

Blah(1, 1) match {
  case Blah(a @ expensive(e), b) if e < 10 => println(a, b, e)
  case _ => println("nothing")
}

Be sure that the expensive is really more expensive that creating an Option object, which is what the above does.

like image 55
axel22 Avatar answered Sep 21 '22 16:09

axel22