Saturday, December 13, 2014
To invoke functions requires us to specify all the function parameters. Scala provides a construct called Partially Applied Functions where a function invocation can be reused by retaining some of the parameters without the need to type them again. Partial application enables conversion of a function with multiple arguments into one with fewer arguments with some values provided in advance.

Let us look at an example to understand the partially applied functions. Here we have basic function multiply to get the product of two numbers. We create two partially applied functions multiplyBy3 and multiplyBy5. Missing argument is substituted with an _ underscore. 

object PartiallyAppliedFunctionsTest {
  def multiply(x: Int, y: Int) : Int = { x * y }
  // Partially applied functions
  val multiplyBy3 = multiply(_:Int, 3)
  val multiplyBy5 = multiply(_:Int, 5)
  def main(args:Array[String]) {
    println("Partial function multiplyBy3 = " + multiplyBy3(6))
    println("Partial function multiplyBy5 = " + multiplyBy5(6))

This example produces the following output.

Partial function multiplyBy3 = 18
Partial function multiplyBy5 = 30

It is also possible to create a partially applied function where all arguments would be passed during function invocation. For example,

val multiply1 = multiply _

Scala provides the syntactic convenience to use single _ (underscore) in this case.

Continue to read more Scala Tutorials.


Contact Form


Email *

Message *

Back to Top