Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Scala Partially Applied Functions

Scala Partially Applied Functions

Scala functions Scala Functions

A Scala partially applied function is an expression where you do not need to supply all the arguments a function requires; you supply only some, or none, of them.

In the following example, we print log messages:



import java.util.Date



object Test {

   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)

   }

}

The output of the code above is:



$ scalac Test.scala

$ scala Test

Mon Dec 02 12:52:41 CST 2018----message1

Mon Dec 02 12:52:41 CST 2018----message2

Mon Dec 02 12:52:41 CST 2018----message3

In the example, the log() method takes two parameters: date and message. We call it three times during execution, with the same date value but different messages.

We can use a partially applied function to improve the above: bind the first date parameter, use an underscore (_) for the second parameter to stand in for the missing argument list, and assign this new function value to a variable. The example is modified as follows:



import java.util.Date



object Test {

   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)

   }

}

The output of the code above is:



$ scalac Test.scala

$ scala Test

Tue Dec 18 11:25:54 CST 2018----message1

Tue Dec 18 11:25:54 CST 2018----message2

Tue Dec 18 11:25:54 CST 2018----message3

Scala functions Scala Functions