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
Scala uses square brackets everywhere to refer to types, in some predictable ways, in some rather hairy ways, which hopefully we can avoid. Parentheses are used around the index, which varies from 0 to the the length of the array −1, as in most programming languages.
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
Scala - Functions with Named Arguments Named arguments allow you to pass arguments to a function in a different order. The syntax is simply that each argument is preceded by a parameter name and an equals sign. Try the following program, it is a simple example to show the functions with named arguments.
A parameterless method is a function that does not take parameters, defined by the absence of any empty parenthesis. Invocation of a paramaterless function should be done without parenthesis.
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) {
..
..
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With