Given snippet composes of method calls, which return an option type. I'd like to call the next method if previous call returned None. I'm able to accomplish this with this snippet
def amountToPay : Option[TextBoxExtraction] =
getMaxByFontsize(keywordAmountsWithCurrency) match {
case None => getMaxByFontsize(keywordAmounts) match {
case None => highestKeywordAmount match {
case None => getMaxByFontsize(amountsWithCurrency) match {
case None => highestAmount
case some => some
}
case some => some
}
case some => some
}
case some => some
}
but it looks quite messy. So I hope there is abetter way to do it.
Yep, orElse
is a little cleaner:
def amountToPay : Option[TextBoxExtraction] =
getMaxByFontsize(keywordAmountsWithCurrency)
.orElse(getMaxByFontsize(keywordAmounts))
.orElse(highestKeywordAmount)
.orElse(getMaxByFontsize(amountsWithCurrency))
.orElse(highestAmount)
You could also just put the items in a Seq
and then use something like xs.reduceLeft(_ orElse _)
or xs.flatten.headOption.getOrElse(highestAmount)
.
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