Scala: Partial application

Learn
2 min readJan 4, 2022

Partial application of a function is when a partial set of parameters is passed into a function but there are still a few parameters to be passed in to fully apply the function.

val multiply: (Int, Int, Int) => Int 
= (n1 , n2, n3) => n1 * n2 * n3
val tenTimesProduct = multiply(10,_,_)
val fiveHundredTimes = tenTimesProduct(50,_)
println(multiply(2,3,4))
println(tenTimesProduct(5,6))
println(fiveHundredTimes(6))
24
300
3000

Say, you have a function from some library, for multiplying three numbers. What you really needed though was a function that takes two numbers as inputs and gives their product times ten. If you were programming in imperative style, you would define a new method which takes two arguments and internally call the library method with one of the arguments hard-coded as 10, and then pass through the other two arguments to the library method.

Partial application technique achieves similar result. You define a function that has the invocation of the original multiply method with “10” as the first argument and underscores to represent the parameters that have not been applied yet.

This can be taken to multiple levels, and each level can have multiple flavors. Multiple flavors would be like having one flavor multiply by 10 and another flavor multiply by 20. Multiple levels would mean that from the derived function with two open arguments and 10 as the fixed 3rd argument, you can create one more function with one of the two remaining ones determined/fixed with a specific value, and leaving just one argument open.

In imperative programming world, the namespace gets polluted for every such flavor added with new defined method names that would get associated with the class where these need to be defined.

Partial application in functional programming world would be so much lighter. This technique lets you re-purpose generic library functions where you establish additional invariants, and then use it as a function more closely suited to your problem solving space.

--

--