Scala partially applied function
A partially applied function, as its name says, is a function where arguments of functions can be applied partially, and as a result it provides another function that still “expects” to get its missing arguments.If the function is called with all its parameters, then it is said to be “fully applied”. If some of the parameters are missing, then the function is said to be “partially applied”.
Few points to understand the use of partially applied functions:
- This is helpful in transforming a function with many arguments to a function with less arguments.
- It is useful in those scenarios where some of the arguments of a functions will always be the same.
- We can safeguards our code by only exposing our partially applied function, so no one else can provide incorrect arguments by mistake.
- It makes code easier to use for other users.
We use an underscore( _ ) as a placeholder for missing arguments. We can use underscore for individual arguments or for the whole list of arguments. Let’s see below an example to understand it.
showNumbers.foreach(x=>println(x))
The above statement prints all values of the list showNumbers, but we can use underscore in the above statement as given below and it will print the same result.
showNumbers.foreach(println _)
Note: There should be space between function name and underscore, as after print there is a space.
Let’s understand it with some more example. Suppose, we have a function named as sum having three arguments. We can create partially applied function by passing underscore which can be passed for some or all the missing arguments. As in the below example, we are passing it for all 3 arguments.
object add {
def main(args: Array[String]): Unit = {
def sum(a: Int, b: Int, c: Int) = a + b + c
val a = sum _ //partially Applied function for all 3 arguments
print(a(1,2,3))
}
}
Output: 6
Underscore can also be passed for individual arguments, but arguments type needs to be mentioned in that case. In the below example, we are passing only first 2 arguments.
object add {
def main(args: Array[String]): Unit = {
def sum(a: Int, b: Int, c: Int) = a + b + c
val a = sum(1,2,_:Int) //partially Applied function for 3rd argument
print(a(3)) //passing 3rd missing arguments
}
}
Output: 6