Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to chain methods which return an Option-Type in a way like getOrElse does but keeps the option-type

Tags:

scala

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.

like image 375
Andreas Neumann Avatar asked May 02 '12 11:05

Andreas Neumann


1 Answers

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).

like image 149
Travis Brown Avatar answered Nov 03 '22 04:11

Travis Brown