user3103957
user3103957

Reputation: 848

Scala functional 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.

Upvotes: 7

Views: 101

Answers (2)

radrow
radrow

Reputation: 7159

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)

Upvotes: 3

Mario Galic
Mario Galic

Reputation: 48430

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

Upvotes: 9

Related Questions