如何在scala中调用具有另一个函数作为参数的函数?

时间:2018-11-21 21:49:08

标签: scala

请告知我如何调用以下函数,该函数具有参数之一。

def totalCostWithDiscountFunctionParameter(donutType: String)(quantity: 
       Int)(f: Double => Double): Double = {
  println(s"Calculating total cost for $quantity $donutType")
  val totalCost = 2.50 * quantity
  f(totalCost)
}

1 个答案:

答案 0 :(得分:1)

首先创建一个函数:

val discountByTenPercent: Double => Double =
  priceBeforeDiscount => 0.9 * priceBeforeDiscount

然后调用作为参数之一的函数:

totalCostWithDiscountFunctionParameter("...")(5)(discountByTenPercent)

当然,您也可以在同一行中创建函数:

totalCostWithDiscountFunctionParameter("...")(5)(priceBeforeDiscount => 0.9 * priceBeforeDiscount)

如果参数列表仅包含一个需要用作函数的参数,则还可以使用花括号代替括号:

totalCostWithDiscountFunctionParameter("...")(5) { priceBeforeDiscount =>
  0.9 * priceBeforeDiscount
}

顺便说一句,“具有另一个函数作为参数的函数”被称为“高阶函数”。

相关问题