Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I store an intermediate result in an Scala case match?

Tags:

scala

Say I have this:

def expensiveTest(t: String): Option[Int] = {...}
// myList: List[String]
myList.collectFirst {
  case x if expensiveTest(x).isDefined => expensiveTest(x).get
}

Something like this works, but... I have to call expensiveTest() twice. Is there a way to save the result of the guard's call to expensiveTest to use on the right side of the =>?

like image 360
Greg Avatar asked May 07 '26 10:05

Greg


1 Answers

Switching the List to a lazy Stream and using a map/head could be an alternative:

myList.toStream.flatMap { case x => expensiveTest(x) }.head
like image 119
Xavier Guihot Avatar answered May 09 '26 01:05

Xavier Guihot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!