Scala partial function application
Scala partial application of function is an expression, you do not provide all the required parameters of the function, only need to provide in part, or do not provide the required parameters.
The following examples, 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) } }
Implementation of the above code, the output is:
$ scalac Test.scala $ scala Test 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
Example, log () method takes two parameters: date and message. We called three times during program execution, the parameter values are the same date, a different message.
We can use the above method of partial application of function optimization, bound first date parameter, the second parameter to use an underscore (_) to replace the missing argument list, and the index of the new function of the value assigned to the variable. Examples of the above amended 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) } }
Implementation of the above code, the output is:
$ scalac Test.scala $ scala Test 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