Scala Partial Function Application
Scala's partial function application is an expression where you don't need to provide all the arguments that a function requires; you can provide only some, or none at all.
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)
}
}
When the above code is executed, the output will be:
$ 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 program execution, with the same date value and different messages.
We can optimize the above method using partial function application, bind the first date parameter, replace the second parameter with an underscore (_) for the missing parameter list, and assign this new function value 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)
}
}
When the above code is executed, the output will be:
$ 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