Partially Applied Functions

When you invoke a function, you’re said to be applying the function to the arguments. If you pass all the expected arguments, you’ve fully applied the function and you get the result of the application or call. However, if you pass fewer than all the required parameters, you get back another function. This function is called a partially applied function. This gives the convenience of binding some arguments and leaving the rest to be filled in later. Here’s an example:

FunctionValuesAndClosures/Log.scala
 
import​ java.util.Date
 
 
def​ log(date: Date, message: ​String​) = {
 
//...
 
println(s​"$date ---- $message"​)
 
}
 
 
val​ date = ​new​ Date(1420095600000L)
 
log(date, ​"message1"​)
 
log(date, ​"message2"​)
 
log(date, ​"message3"​)

In this code, the log method takes two parameters: date and message. We want to invoke the method multiple times, with the same value for date but different values for message. We can eliminate the noise of passing the date to each call by partially applying that argument to the log method.

In the next code sample, we first bind a value to the date parameter. We use the _ to leave the second parameter unbound. The result is a partially applied function that we’ve stored in the reference logWithDateBound. We can now invoke this new method with only the unbound argument message:

FunctionValuesAndClosures/Log.scala
 
val​ date = ​new​ Date(1420095600000L)
 
val​ logWithDateBound = log(date, _ : ​String​)
 
logWithDateBound(​"message1"​)
 
logWithDateBound(​"message2"​)
 
logWithDateBound(​"message3"​)

Let’s invite the Scala REPL to our party to help us better understand the partially applied function created from the log function:

 
scala> import java.util.Date
 
import java.util.Date
 
 
scala> def log(date: Date, message: String) = println(s"$date ----
 
$message")
 
log: (date: java.util.Date, message: String)Unit
 
 
scala> val logWithDateBound = log(new Date, _ : String)
 
logWithDateBound: String => Unit = <function1>
 
 
scala> :quit

From the details displayed by the REPL we can tell that the variable logWithDateBound is a reference to a function that takes a String as a parameter and returns a Unit as result.

When you create a partially applied function, Scala internally creates a new class with a special apply method. When you invoke the partially applied function, you’re actually invoking that apply method—see Common Scala Collections for more details on the apply method. Scala makes extensive use of partially applied functions when pattern-matching messages that are received from an actor, as you’ll see in Chapter 13, Programming with Actors.

Next we’ll dig into the scope in function values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.244.44