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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With