如何替换Scala中存在的多个副本?

时间:2018-06-28 06:11:31

标签: scala

我有这段代码看起来是根据所选类别的存在来确定服务费的:

def bill(purchasedItems: List[String]): BigDecimal = {
    def totalCost: BigDecimal = purchasedItems.foldLeft(BigDecimal(0))((tot, p) => tot + menu(p).price)

    def serviceChargeRate: BigDecimal = if (purchasedItems.exists(name => menu(name).serviceChargeCategory == PremiumItem)) 1.2
    else if (purchasedItems.exists(name => menu(name).serviceChargeCategory == Food)) 1.1
    else 1.0

    totalCost * serviceChargeRate
  }

我尝试用collectFirst代替它,但是它将与第一项匹配,而不是使用优先顺序来确保使用最高的服务费。

 def bill(purchasedItems: List[String]): BigDecimal = {
    def totalCost: BigDecimal = purchasedItems.foldLeft(BigDecimal(0))((tot, p) => tot + menu(p).price)

    def serviceChargeRate: Option[BigDecimal] = purchasedItems.map(menu(_).serviceChargeCategory) collectFirst {
      case PremiumItem => BigDecimal("1.2")
      case Food => BigDecimal("1.1")
    }

    totalCost * serviceChargeRate.getOrElse(BigDecimal("1.0"))
  }

在Scala中是否有更好,更实用的方法来执行此操作,还是我必须接受if / else块?

谢谢

1 个答案:

答案 0 :(得分:3)

我的建议将遵循以下原则:

def bill(purchasedItems: List[String]): BigDecimal = {
  val  totalCost: BigDecimal = purchasedItems.foldLeft(BigDecimal(0))((tot, p) => tot + menu(p).price)
  val serviceRate: BigDecimal = purchasedItems.map { item ⇒ menu(item).serviceChargeCategory match {
    case "PremiumItem" ⇒ 1.2
    case "Food" ⇒ 1.1
    case _ ⇒ 1.0
}}.max

  totalCost * serviceChargeRate
}