20

给定的片段由方法调用组成,它们返回一个选项类型。如果上一个调用返回 None,我想调用下一个方法。我可以用这个片段来完成这个

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
  }

但它看起来很乱。所以我希望有更好的方法来做到这一点。

4

1 回答 1

33

是的,orElse更干净一点:

def amountToPay : Option[TextBoxExtraction] =
  getMaxByFontsize(keywordAmountsWithCurrency)
    .orElse(getMaxByFontsize(keywordAmounts))
    .orElse(highestKeywordAmount)
    .orElse(getMaxByFontsize(amountsWithCurrency))
    .orElse(highestAmount)

您也可以将项目放在 a 中Seq,然后使用类似xs.reduceLeft(_ orElse _)or的东西xs.flatten.headOption.getOrElse(highestAmount)

于 2012-05-02T11:57:34.950 回答