Scala – Partially Applied Functions

Scala partially applied functions

In this guide, we will discuss Scala Partially Applied Functions. When you invoke a function, you’re said to be applying the function to the arguments. If you pass all the expected arguments, you have fully applied it. If you send only a few arguments, then you get back a partially applied function. This gives you the convenience of binding some arguments and leaving the rest to be filled in later.

Try the following, it is a simple example program to show partially applied functions −

Example

import java.util.Date

object Demo {
   def main(args: Array[String]) {
      val date = new Date
      log(date, "message1" )
      
      Thread.sleep(1000)
      log(date, "message2" )
      
      Thread.sleep(1000)
      log(date, "message3" )
   }

   def log(date: Date, message: String)  = {
      println(date + "----" + message)
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

C:/>scalac Demo.scala
C:/>scala Demo

Output

Mon Dec 02 12:52:41 CST 2013----message1
Mon Dec 02 12:52:41 CST 2013----message2
Mon Dec 02 12:52:41 CST 2013----message3

Here, the log( ) method takes two parameters: date and message. We want to invoke the method multiple times, with the same value for date but different values for message. We can eliminate the noise of passing the date to each call by partially applying that argument to the log( ) method. To do so, we first bind a value to the date parameter and leave the second parameter unbound by putting an underscore at its place. The result is a partially applied function that we’ve stored in a variable.

Try the following example program to invoke this new method with only the unbound argument message.

Example

import java.util.Date

object Demo {
   def main(args: Array[String]) {
      val date = new Date
      val logWithDateBound = log(date, _ : String)

      logWithDateBound("message1" )
      Thread.sleep(1000)
      
      logWithDateBound("message2" )
      Thread.sleep(1000)
      
      logWithDateBound("message3" )
   }

   def log(date: Date, message: String) = {
      println(date + "----" + message)
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Mon Dec 02 12:53:56 CST 2013----message1
Mon Dec 02 12:53:56 CST 2013----message2
Mon Dec 02 12:53:56 CST 2013----message3

Next Topic : Click Here

This Post Has 2 Comments

Leave a Reply