Scala provides a concept called partially applied functions that spares you from writing several lines of code.
Say, you have a function f that accepts 2 arguments. While invoking f you may have to pass both the arguments. In Scala you have an option to invoke f by passing partial list of arguments. You can create a partially applied function of f by passing the first argument alone. Later you can invoke the partially applied function by passing the second argument. Let’s take a close look at it with an example
We have a function that calculates arithmetic progression of n numbers. The function takes in the first number, the common difference and the number of values you want the series to be computed. Here’s the code to do that in Scala
def arithmeticProgression(first:Int,difference:Int,numbers:Int):List[Int]= { var result = List[Int]() 0 to numbers foreach {x=>result = result :+ (first + (x * difference))} result }
The arithmeticProgression method accepts 3 arguments and returns a series list. You can invoke it like this.
println(arithmeticProgression(1,1,10))
The output of the above code will be List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11). Say you want the arithmetic progression of 10 numbers starting from 1 and with varied values for the difference argument. This is how you will do it traditionally
println(arithmeticProgression(1,1,10)) println(arithmeticProgression(1,2,10)) println(arithmeticProgression(1,3,10)) println(arithmeticProgression(1,4,10)) println(arithmeticProgression(1,5,10))
You can notice that the second parameter is the only varying argument here. The first parameter has a constant value 1 and the third parameter also has 10 as its value. You can rewrite it as shown here.
1 to 5 foreach {i=>println(arithmeticProgression(1,i,10))}
This code still makes too much noise. Let’s rewrite it using partially applied function here.
def ap10 = arithmeticProgression(1,_:Int,10:Int) 1 to 5 foreach {i=>println(ap10(i))}
We’ve created a partially applied function called ap10 by passing 1 and 10 for the first and third arguments and an underscore for the second argument. We can now invoke this function just by passing any integer value to the second parameter alone by writing ap10(1) or ap10(2) and so on.
If you want to change the first and third parameters and keep the difference as constant you can define a partial function as like this.
def ap = arithmeticProgression(_:Int,2:Int,_:Int) println(ap(1,20))
Partially applied functions in scala serve as useful feature for implementing the method overloading concept in OO languages.