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 =>?
Switching the List to a lazy Stream and using a map/head could be an alternative:
myList.toStream.flatMap { case x => expensiveTest(x) }.head
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