Note: jump down to “Question” below if you just want to skip the context
When giving talks on Scala I pretty much give “toy problems” like the one below as examples of Partially Applied Functions.
def multiply(x:Int, y:Int): Int = x * y
val x5 = multiply(5, _:Int)
x5(10) //produces 50
This example does help, however it’s tough for me to explain a general “this is when you’d recognize when to use a partially applied function”.
Question: Anyone have their own way of successfully explaining Partially Applied Functions that really hits home for Java (or other OO language) developers?
Suppose you want to apply sales tax.
Now suppose you want to make a bunch of purchases in New York.
You get maximal code reuse from the original method, yet maximal convenience for repetitive tasks by not having to specify the parameters that are (locally) always the same.
People often try to solve this with implicits instead:
Don’t do it! (Not without careful consideration.) It’s hard to keep track of which implicit val happens to be around at the time. With partially applied functions, you get the same savings of typing, plus you know which one you’re using because you type the name every time you use it!