What is the difference of the following two function definitions in Scala:
1) def sum(f: Int => Int)(a: Int, b: Int): Int = { <code removed> }
2) def sum(f: Int => Int, a: Int, b: Int): Int = { <code removed> }
?
SBT's console REPL gives different value for them so looks if they are somehow different:
sum: (f: Int => Int, a: Int, b: Int)Int
sum: (f: Int => Int)(a: Int, b: Int)Int
The first definition is curried, so that you can provide a
and b
at another time.
For instance, if you know the function you want to use in the current method, but don't yet know the arguments, you can use it so:
def mySum(v: Int): Int = v + 1
val newsum = sum(mySum) _
At this point, newsum
is a function that takes two Int
s and returns an Int
.
In the context of summing it doesn't seem to make much sense; however, there have been plenty of times I've wanted to return different algorithms for parts of a program based upon something I know now, but don't know (or have access to) the parameters yet.
Currying buys you that feature.
Scala functions support multiple parameter lists to aid in currying. From your first example, you can view the first sum
function as one that takes two integers and returns another function (i.e. curries) which can then take an Int => Int
function as an argument.
This syntax is also used to create functions that look and behave as new syntax. For example, def withResource(r: Resource)(block: => Unit)
can be called:
withResource(res) {
..
..
}
来源:https://stackoverflow.com/questions/19036682/different-brackets-style-on-scala-function-definition-parameter-list