I'm a Scala beginner. Can someone explain me what is the difference (except syntax) between these two lines of code (though they return the same result)? I wrote them practicing literal functions and try to find out if there is anything up 'behind the scene'?
val literal1 = (fn: Int => Int, x: Int) => fn(x)
val literal2 = (fn: Int => Int) => (x: Int) => fn(x)
I see that there is a possibility of passing arguments into functions in different ways. But does it really matter which way I choose (except of currying case)?
literal1(p => p + 1, 2) /*3*/
literal2(p => p + 1)(2) /*3*/
These two values have different types:
In other words,
literal1is a function that takes two arguments—a function that takes anIntand returns anInt, and anInt—and returns anInt.On the other hand,
literal2is a function that takes one argument—a function that takes anIntand returns anInt, and returns a function that takes anIntand returns anInt.Other than the different calling convention, the second form allows you to easily partially apply the first parameter, returning a function that takes an
Intand returns anInt:Doing the same with the first form requires very slightly more complex syntax:
The first form can be transformed automatically to the second using its
curriedmethod:Note that it is conventional in Scala for functions and methods that take a single function argument to specify it as the final argument in a curried format, as this allows for a convenient syntax for a multi-line lambda:
Output: