9.8. Creating Partial Functions
Problem
You want to define a function that will only work for a subset of possible input values, or you want to define a series of functions that only work for a subset of input values, and combine those functions to completely solve a problem.
Solution
A partial function is a function that does not provide an answer for every possible input value it can be given. It provides an answer only for a subset of possible data, and defines the data it can handle. In Scala, a partial function can also be queried to determine if it can handle a particular value.
As a simple example, imagine a normal function that divides one number by another:
val
divide
=
(
x
:
Int
)
=>
42
/
x
As defined, this function blows up when the input parameter is zero:
scala> divide(0)
java.lang.ArithmeticException: / by zero
Although you can handle this particular situation by catching and
throwing an exception, Scala lets you define the divide
function as a PartialFunction
. When doing so, you also
explicitly state that the function is defined when the input parameter
is not zero:
val
divide
=
new
PartialFunction
[
Int
,Int
]
{
def
apply
(
x
:
Int
)
=
42
/
x
def
isDefinedAt
(
x
:
Int
)
=
x
!=
0
}
With this approach, you can do several nice things. One thing you can do is test the function before you attempt to use it:
scala>divide.isDefinedAt(1)
res0: Boolean = true scala>if (divide.isDefinedAt(1)) divide(1)
res1: AnyVal = 42 scala>divide.isDefinedAt(0)
res2: Boolean = false
This isn’t all you can do ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.