Scala 这是“按名称”函数参数吗?为什么通配符是可选的?
我正在学习教程,我看到了以下代码:Scala 这是“按名称”函数参数吗?为什么通配符是可选的?,scala,Scala,我正在学习教程,我看到了以下代码: println("\nStep 1: How to define a higher order function which takes another function as parameter") def totalCostWithDiscountFunctionParameter(donutType: String)(quantity: Int)(f: Double => Double): Double = { pr
println("\nStep 1: How to define a higher order function which takes another function as parameter")
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)
}
println("\nStep 2: How to define and pass a def function to a higher order function")
def applyDiscount(totalCost: Double): Double = {
val discount = 2 // assume you fetch discount from database
totalCost - discount
}
println(s"Total cost of 5 Glazed Donuts with discount def function = ${totalCostWithDiscountFunctionParameter("Glazed Donut")(5)(applyDiscount(_))}")
println("\nStep 3: How to define and pass a val function to a higher order function")
val applyDiscountValueFunction = (totalCost: Double) => {
val discount = 2 // assume you fetch discount from database
totalCost - discount
}
println(s"Total cost of 5 Glazed Donuts with discount val function = ${totalCostWithDiscountFunctionParameter("Glazed Donut")(5)(applyDiscountValueFunction)}")
作者说:
该函数有一个by-name参数,该参数应为具有Double类型参数的函数,并且还将返回Double类型的参数
这是真的吗?这里的按值参数是什么?函数是否被延迟计算,从而使其成为按名称参数?这是真的吗
为什么作者在传入applyDiscount
时使用通配符,而在传入applydiscountValueFunction
时不使用通配符?这两种方法都不使用通配符运算符。applyDiscount(41;
使用匿名函数的占位符语法将方法转换为函数
每当需要函数类型并传递方法时,编译器(使用一种称为eta扩展的技术)就可以自动执行此过程,这与示例中的情况完全相同
(有关更深入的讨论,请参阅以下答案:)
所以你说得对
totalCostWithDiscountFunctionParameter("Glazed Donut")(5)(applyDiscount)
无论如何都可以工作,因为编译器会自动将applyDiscount
转换为函数
根据by-name参数,作者所调用的
by-name
参数(参数f
)实际上只是Double=>Double
类型的参数,因此他使用的术语似乎不正确
Scala中的按名称参数使用=>
表示,如下所示:
def someMethod(someParam: => Double): Double = // ...
在本例中,
someParam
是一个按名称参数,这意味着它不会在调用站点进行计算。在句子中:函数有一个按名称参数,您指的是哪个函数?applyDiscount(41;
不是eta扩展。我已经更新了答案,更正了它,并将它与您的链接起来