I have the following piece of code:
foo collect {
case x if check(expensive(x)) => do_something(expensive(x))
}
To prevent expensive()
being called twice, I can do this:
object expensive_helper {
def unapply[A, B](x: A): Option[B] =
???
}
But, this is pretty verbose. Is there a better way?
I have this helper in my common utils:
case class matches[A, B](f: A => B)(check: B => Boolean) {
def unapply(a: A): Option[B] = Option(f(a)).filter(check)
}
Here’s how to use it:
val x = "abcd"
val base64 = matches((s: String) => Try(s.base64UrlDecode))(_.isSuccess)
x match {
case base64(y) => println("Decoded" + y)
case _ => println("Could not decode" + x)
}