There is another way we can write the method, where each parameter is enclosed in parenthesis. For example, the modBy2
method can also be written as follows:
scala> def modBy2(n: Int)(d: Int) = n % d modBy2: (n: Int)(d: Int)Int scala> modBy2(10)(3) res0: Int = 1
This form is called currying. Currying allows us to turn a function that expects two arguments into a function that expects only one.
By applying currying to modBy2
, we get back another function:
scala> modBy2 _ res3: Int => (Int => Int) = <function1>
This is a function that takes in an Int
parameter, n
. It returns another function, which takes yet another Int
parameter, d
. This function finally returns the result, which is Int
. Well, here is the diagrammatic representation of currying:
If we just specify the value for n
, we get a partially applied function again:
scala> modBy2(10) _ res5: Int => Int = <function1> scala> val p = modBy2...