subho subho - 3 months ago 17
Scala Question

sequence of scala function return methods

I am new to scala and learning scala.

scala> def first(x: Int)= (y: Int) => x + y
first: (x: Int)Int => Int

scala> val second= first(1)
second: Int => Int = <function1>

scala> second(2)
res8: Int = 3


I want to understand the above function, first 1 is passed as an argument and returns second function it does nothing , just stores the value of x=1 , then the second val, which represents the second function is called as 2, then the value of Y is stored as 2 , then it called the return => x + y,
which evaluates to 1+2 and gives 3 as result.

Please let me know if my understanding is correct.
If anyone can add something to it or correct if I am wrong.

Thanks and Regards,

Answer
scala> def first(x: Int)= (y: Int) => x + y // 1
first: (x: Int)Int => Int

scala> val second= first(1) // 2
second: Int => Int = <function1>

scala> second(2) // 3
res8: Int = 3

In case 1, you have created a function called first which accepts an integer and returns a function which accepts an integer and adds it to integer you passed to first.

In case 2, you apply 1 to the first function to return a function which accepts an integer and adds 1 to it. You have 'labelled' this function second. This is equivalent to (y : Int) => 1 + y.

In case 3, you apply 2 to the second function which returns 3 as expected.

Comments