You can write an extractor for the type x(assumed here InputType):
object Expensive {
def unapply(x: InputType): Option[OutputType] = expensiveCalculation(x)
}
Now you can use it according to your template:
fooList match {
case _ :: Expensive(output) :: _ => ...
case _ :: x :: _ => ...
}
However, this is a cumbersome way to do what you want if you do it for many calculations (you need to define an extractor each time).
You can do this once and for all by specifying the following:
case class Comput[-A, +B](f: A => Option[B]) {
def unapply(a: A): Option[B] = f(a)
}
Now you can use it as follows:
val intString = "10"
val IntOf = Comput[String, Int](s => Try(s.toInt).toOption)
intString match {
case IntOf(x) => x
case other => 0
} // returns 10: Int
IntOf, (, , ).