How can I create an anonymous and curried function in Scala? The following two failed:
scala> (x:Int)(y:Int) => x*y
<console>:1: error: not a legal formal parameter
(x:Int)(y:Int) => x*y
^
scala> ((x:Int)(y:Int)) => x*y
<console>:1: error: not a legal formal parameter
((x:Int)(y:Int)) => x*y
^
Currying is the process of converting a function with multiple arguments into a sequence of functions that take one argument. Each function returns another function that consumes the following argument.
In Scala, An anonymous function is also known as a literal function. A function that does not contain a name is known as an anonymous function. An anonymous function provides a lightweight function definition. It is useful when we want to create an inline function.
A function doesn't need any object and is independent, while the method is a function, which is linked with any object. We can directly call the function with its name, while the method is called by the object's name. Function is used to pass or return the data, while the method operates the data in a class.
It is a technique in functional programming, transformation of the function of multiple arguments into several functions of a single argument in sequence. The translation of function happens something like this, function simpleFunction(param1, param2, param3, …..)
To create a curried function write it as if it were multiple functions (that's actually the case ;-) ).
scala> (x: Int) => (y: Int) => x*y
res2: Int => Int => Int = <function1>
This means you have a function from Int to a function from Int to Int.
scala> res2(3)
res3: Int => Int = <function1>
alternatively you can write it like this:
scala> val f: Int => Int => Int = x => y => x*y
f: Int => Int => Int = <function1>
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