Warm tip: This article is reproduced from serverfault.com, please click

其他-Scala:Curying vs闭包

(其他 - Scala: currying vs closure)

发布于 2020-11-29 09:12:56

我可以使用闭包来定义如下函数:

def product(x: Int) = (y: Int) => x * y
val productBy3 = product(3)
println(productBy3(6)) // 18

或者,使用currying:

def curriedProduct(x: Int)(y: Int) = x * y
val productBy3 = curriedProduct(3)_
println(productBy3(6)) // 18

一种方法相对于其他方法有什么优点/缺点?

Questioner
Mandroid
Viewed
11
Martijn 2020-11-29 18:10:05

第一个是返回函数的方法的示例。第二个示例是带有多个参数列表的方法的示例。

你使用它们的方式没有任何区别。

当称为时product(3)(6),第二个可能会更快一些,但不会达到通常需要关注的程度。

当预期的调用方式为with时product(3)我将使用第一种形式;如果正常的调用方式为,则将使用第二种形式product(3)(6)

最后,我想建议一下

def product(i: Int, j: Int) = i * j
val productBy3 = product(3, _)
println(productBy3(6)) //18

在这种情况下,我真的没有看到使用第二种形式代替这种替代方法或第一种替代方法的任何好处。使用多个参数列表可能有助于在scala 2中键入推断(请参阅https://docs.scala-lang.org/tour/multiple-parameter-lists.html),但是无论如何,这里没有问题。