English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Scala Partial Application Functions

Scala Functions

Scala partial application functions are an expression where you do not need to provide all the parameters required by the function, just provide some, or not provide the required parameters.

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

Execute the above code, the output 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 called it three times during program execution, with the same date value and different messages.

We can optimize the above method using partial application functions, binding the first date parameter, and replacing the missing parameter list with an underscore (_) and assigning the new function value's index to a variable. The modified example is 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)
   }
}

Execute the above code, the output 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