简体   繁体   English

Scala:柯里化与闭包

[英]Scala: currying vs closure

I can use closure to define function like this:我可以使用闭包来定义 function ,如下所示:

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

OR, using currying:或者,使用柯里化:

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

Any advantage/disadvantage one approach has over other?一种方法比其他方法有什么优势/劣势?

The first is an example of a method returning a function.第一个是返回 function 的方法示例。 The second is an example of a method with multiple parameter lists.第二个是具有多个参数列表的方法的示例。

The way you use them, there is no difference.你使用它们的方式,没有区别。

When called as product(3)(6) , the second may be a bit faster, but not to an extent that would normally be a concern.当称为product(3)(6)时,第二个可能会快一点,但不会达到通常会引起关注的程度。

I would use the first form when the expected way to call it would be with product(3) , and use the second form if the normal way to call it would be product(3)(6) .当预期的调用方式是product(3)时,我会使用第一种形式,如果正常的调用方式是product(3)(6) ,我会使用第二种形式。

Lastly, I'd like to suggest the possibility of最后,我想提出一种可能性

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

I don't really see any upsides of using the second form instead of either this alternative or the first alternative in this situation.在这种情况下,我真的没有看到使用第二种形式而不是这种替代方案或第一种替代方案的任何好处。 Using multiple parameter lists may help type inference in scala 2 (see https://docs.scala-lang.org/tour/multiple-parameter-lists.html ), but there is no problematic inference here anyway.使用多个参数列表可能有助于在 scala 2 中进行类型推断(参见https://docs.scala-lang.org/tour/multiple-parameter-lists.ZFC35FDC70D5FC69D269883A822C7A53无论如何,这里的推断没有问题)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM