我正在尝试将
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.
}