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

Scala: currying vs closure

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

I can use closure to define function like this:

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?

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

The first is an example of a method returning a 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.

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).

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.