Scala learning (7) Scala currying and its application

1. Concept

Currying (named after the logician Haskell Brooks Curry) refers to the process of turning a function that takes two arguments into a new function that takes one argument. The new function returns a function that takes the original second parameter as an argument. There are subtle differences between methods and functions in Scala, and usually the compiler will automatically complete the conversion of methods to functions.

Second, the form of currying in Scala

The definition form of curried methods in Scala is similar to that of ordinary methods. The difference is that curried methods have multiple sets of parameter lists, and each set of parameters is enclosed in parentheses, for example:


The mysum method has two sets of parameters, namely (x: Int) and (y: Int).

The curried function type corresponding to the mysum method is:

Int => Int = >Int
The type declaration of a curried function is right-associative, i.e. the above type is equivalent to:
Int => (Int = >Int)

Indicates that if the function accepts only one Int parameter, it returns a function of type Int => Int, which is also consistent with the process of currying.

3. Examples

The above code defines a curried method. In Scala, functions can be directly manipulated, but methods cannot be directly manipulated. Therefore, before using the curried method, it needs to be converted into a curried function. The easiest way is to use the syntactic sugar provided by the compiler:


The transformation can also be achieved using the partially applied function trick in Scala, but please note that the transformation is not a curried function, but a normal function that takes two (rather than two) arguments


Pass in a parameter:


That is, a function that takes an Int parameter and returns an Int. Continue to pass in the second parameter:


Both sets of parameters have been passed in, and an Int type result is returned

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326308431&siteId=291194637