Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala functional literals

Tags:

scala

literals

  1. val x = (x:Int, y:Int) => (_:Int) + (_:Int)
  2. 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.

like image 538
user3103957 Avatar asked May 19 '19 15:05

user3103957


People also ask

How do you pass anonymous function in Scala?

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...!!" }

What is literal function go?

A function literal is a function declared inline without a name. In all other languages, this is called an anonymous function.

What is string literal in Scala?

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 .

What is lambda function in Scala?

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.


2 Answers

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
like image 112
Mario Galic Avatar answered Nov 01 '22 09:11

Mario Galic


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)
like image 34
radrow Avatar answered Nov 01 '22 08:11

radrow