Scala Partially Applied Functions

Scala 函数Scala Functions

A Scala partially applied function is an expression where you do not need to provide all the arguments required by the function; you only need to provide some, or none, of the required arguments.

In the following example, we print log information:

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)
   }
}

Executing the above code produces the following output:

$ 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 called it three times during program execution, with the same date value each time, but different message values.

We can use a partially applied function to optimize the above method by binding the first date parameter, using an underscore (_) to replace the missing parameter list for the second parameter, and assigning this new function value to a variable. The above 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)
   }
}

Executing the above code produces the following output:

$ 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 函数Scala Functions

Other Extensions