val x = (x:Int, y:Int) => (_:Int) + (_:Int)
val y = (_:Int) + (_:Int)
In the above two functional literals in Scala, when I call the first one ( e.g: x(2,3) ), it is not returning the sum. Rather it returns another result, say res0. When I call res0(2,3), then it return me the sum. Whereas the second one, returns the answer in the very first call (say: y(2,3) gives me 5).
Can someone please explain why the first one does not return me the sum (which is 5) in the first call itself.
I tried in REPL.
We can define multiple arguments in the anonymous function. We are allowed to define an anonymous function without parameters. In Scala, We are allowed to pass an anonymous function as a parameter to another function. var myfun 1 = () => { "Welcome to GeeksforGeeks...!!" }
A function literal is a function declared inline without a name. In all other languages, this is called an anonymous function.
A string literal is a sequence of characters in double quotes. The characters are either printable unicode character or are described by escape sequences. If the string literal contains a double quote character, it must be escaped, i.e. "\"" . The value of a string literal is an instance of class String .
Scala lambda functions are anonymous functions. They reduce the line of code and make the function more readable and convenient to define. We can also reuse them. We can use this lambda function to iterate our collection data structure and performed any kind of operation on them.
It might be helpful to write out the full types of x
and y
like so
val x: (Int, Int) => (Int, Int) => Int =
(a: Int, b: Int) => (_: Int) + (_: Int)
val y: (Int, Int) => Int =
(_: Int) + (_: Int)
Here we see when x
is applied to two arguments it returns yet another function of type
(Int, Int) => Int
Note that shorthand
(_: Int) + (_: Int)
is equivalent to
(a: Int, b: Int) => a + b
val x = (x:Int, y:Int) => (_:Int) + (_:Int)
Is equivalent to
val x = (x : Int, y : Int) => ((arg1:Int, arg2:Int) => (arg1:Int) + (arg1:Int))
While
val y = (_:Int) + (_:Int)
Is equivalent to
(x:Int, y:Int) => (x:Int) + (x:Int)
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