I have this method, given a sequence of instruments, it queries a web service to get the old price and the new price. Then it will use a function to see if the price difference is significant. It will return the first instrument with a significant price difference. Now, my problem is it always returns None unless I add an explicit return statement as below.
I understand scala returns the last expression to be evaluated. Is there a way to refactor this code to avoid an explicit return.
In what situations we cannot avoid having explicit return statements?
// without explicit return
def findEquty[A](instruments: Seq[A], change: (Double, Double) => Boolean): Option[A] = {
for (instrument <- instruments) {
val oldPrice = getOldPrice(instrument)
val newPrice = getNewPrice(instrument)
if (change(oldPrice, newPrice)) Some(instrument)
}
None
}
// with explicit return
def findEquty[A](instruments: Seq[A], change: (Double, Double) => Boolean): Option[A] = {
for (instrument <- instruments) {
val oldPrice = getOldPrice(instrument)
val newPrice = getNewPrice(instrument)
if (change(oldPrice, newPrice)) return Some(instrument)
}
None
}