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:
valdivide=(x:Int)=>42/x
As defined, this function blows up when the input parameter is zero:
scala> divide(0)
java.lang.ArithmeticException: / by zeroAlthough 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:
valdivide=newPartialFunction[Int,Int]{defapply(x:Int)=42/xdefisDefinedAt(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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access