如何将匿名类实现转换为lambda风格?

问题描述 投票:0回答:0

我正在尝试将

promotion2Plus1Anon
替换为
promotion2Plus1Lambda
(Lambda Scala 风格),但不幸的是它抛出了异常“前向引用扩展了值 myFormula 的定义”。 我做错了什么?

trait Formula {
  def formula(seq: Seq[Double], sum: Double): Double
}

val promotion2Plus1Anon: Formula = new Formula { // Anonymous class
  override def formula(seq: Seq[Double], sum: Double): Double = {
    val prices: Seq[Double] = seq.sorted
    if (prices.isEmpty) 0
    else if (prices.tail.isEmpty) sum + prices.head
    else if (prices.tail.tail.isEmpty) sum + prices.head + prices.tail.head
    else formula(prices.tail.tail.tail, sum + prices.head + prices.tail.head)
  }
}

val promotion2Plus1Lambda: Formula = (seq: Seq[Double], sum: Double) => {
  val prices: Seq[Double] = seq.sorted
  if (prices.isEmpty) 0
  else if (prices.tail.isEmpty) sum + prices.head
  else if (prices.tail.tail.isEmpty) sum + prices.head + prices.tail.head
  else promotion2Plus1Lambda.formula(prices.tail.tail.tail, sum + prices.head + prices.tail.head) // error: To fix this error, you can define the formula function directly inside myFormula instead of referring to it from Formula.
}
scala functional-programming anonymous-class
© www.soinside.com 2019 - 2024. All rights reserved.