Scala Partial Functions
Partial functions are often used to define a total function in parts:
In this usage, the partial functions are attempted in order of concatenation with the orElse method. Typically, a final partial function is provided that matches all remaining cases. Collectively, the combination of these functions acts as a total function.
This pattern is typically used to separate concerns where a function may effectively act a dispatcher for disparate code paths. This is common, for example, in the receive method of an Akka Actor.
Usage with `collect`
While partial function are often used as convenient syntax for total functions, by including a final wildcard match (case _), in some methods, their partiality is key. One very common example in idiomatic Scala is the collect method, defined in the Scala collections library. Here, partial functions allow the common functions of examining the elements of a collection to map and/or filter them to occur in one compact syntax.
Assuming that we have a square root function defined as partial function:
We can invoke it with the collect combinator:
effectively performing the same operation as:
There are several things to note in the example above:
•The left-hand side of each pattern match effectively selects elements to process and include
in the output. Any value that doesn't have a matching case is simply omitted.
• The right-hand side defines the case-specific processing to apply.
•Pattern matching binds variable for use in guard statements (the if clauses) and the righthand side.