CHAPTER 4 ■ FUN WITH FUNCTIONS, AND NEVER HAVING TO CLOSE THAT JDBC CONNECTION
97
Partial Application and Functions
Methods and functions are different things. In Scala, everything except a method is an
instance; therefore methods are not instances. Methods are attached to instances and can
be invoked on instances. Functions are instances that implement a
FunctionNN trait, where
NN is the number of parameters the function takes. There’s nothing magic at runtime
about functions. However, at compile time, there is plenty of syntactic sugar that makes
the number of characters required to create a function very, very small.
Scala traces its roots to functional languages including ML and Haskell. In these
languages, a function that takes two
Ints and returns a String is the same as a function that
takes an
Int and returns a function that takes an Int and returns a String. Thus (Int, Int)
=> String and Int => Int => String are the same in Haskell but not in Scala. Haskell makes
it easy to create a new function by applying the first parameter to a function that will return
a new function that can then be passed around or applied. This is called partial application
because some of the parameters are passed to the function rather than all the parameters
being applied to the function. Scala requires a separate syntax to automatically generate
partially applied functions.
In Scala, we can build partially applied functions out of methods:
scala> def plus(a: Int, b: Int) = "Result is: "+(a + b)
plus: (Int,Int)java.lang.String
scala> val p = (b: Int) => plus(42, b)
p: (Int) => java.lang.String = <function>
In the previous code, we’ve turned a method that takes two Int parameters into a func-
tion that supplies the first parameter, in this case
42, but that needs a second Int parameter
to fulfill the requirements for the application of
plus. In this case, p is a partial application of
plus, and we can complete the application by supplying an Int to p.
It turns out that partial application of functions is a common thing. It allows you to
build up functions based on values in a given scope and allows for better code reuse. Scala
19897ch04.fm Page 97 Thursday, April 23, 2009 4:35 PM