Scala Partially Applied Function

Partially Applied Function

 
When you give only a subset of the parameters to the function, the result of the expression is a partially applied function.

Partially applied function are useful when you want to reuse a function invocation and retain some of the parameters to avoid typing them in again

 

Creating Partially Applied Function

 
If you want to retain some of the parameters, you can partially apply the function by using the wildcard operator to take the place of one of the parameters.

The wildcard operator here requires an explicit type specification.

 

Lets the consider the following add function :

val add = (x: Int, y: Int) => x + y

This function takes 2 Int parameters and can be invoked by passing both arguments.

For example, add(5,10)

 

We can create a Partially applied function as :

val partialAdd = add(5,_:Int)

Now partialAdd is a partially applied function.

 

Invoking Partially Applied Function

 
We can invoke partialAdd to add any number to 5, i.e.,

partialAdd(10)

The result will be 15.
 
The first argument 5 was passed into the original add function and the new function named partiallyAdd was created, which is a partially applied function; then, the second argument 10 was passed into partiallyAdd.

Since all the parameters are provided, the original function is executed, providing the result 15.

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags