On this page
Trait PartialFunction.PartialFunction
trait PartialFunction[-A, +B] extends A => B
A partial function of type PartialFunction[A, B] is a unary function where the domain does not necessarily include all values of type A. The function isDefinedAt allows to test dynamically if a value is in the domain of the function.
Even if isDefinedAt returns true for an a: A, calling apply(a) may still throw an exception, so the following code is legal:
val f: PartialFunction[Int, Any] = { case x => x / 0 } // ArithmeticException: / by zero
It is the responsibility of the caller to call isDefinedAt before calling apply, because if isDefinedAt is false, it is not guaranteed apply will throw an exception to indicate an error condition. If an exception is not thrown, evaluation may result in an arbitrary value.
The usual way to respect this contract is to call applyOrElse, which is expected to be more efficient than calling both isDefinedAt and apply.
The main distinction between PartialFunction and scala.Function1 is that the user of a PartialFunction may choose to do something different with input that is declared to be outside its domain. For example:
val sample = 1 to 10
def isEven(n: Int) = n % 2 == 0
val eveningNews: PartialFunction[Int, String] = {
case x if isEven(x) => s"$x is even"
}
// The method collect is described as "filter + map"
// because it uses a PartialFunction to select elements
// to which the function is applied.
val evenNumbers = sample.collect(eveningNews)
val oddlyEnough: PartialFunction[Int, String] = {
case x if !isEven(x) => s"$x is odd"
}
// The method orElse allows chaining another PartialFunction
// to handle input outside the declared domain.
val numbers = sample.map(eveningNews orElse oddlyEnough)
// same as
val numbers = sample.map(n => eveningNews.applyOrElse(n, oddlyEnough))
val half: PartialFunction[Int, Int] = {
case x if isEven(x) => x / 2
}
// Calculating the domain of a composition can be expensive.
val oddByHalf = half.andThen(oddlyEnough)
// Invokes `half.apply` on even elements!
val oddBalls = sample.filter(oddByHalf.isDefinedAt)
// Better than filter(oddByHalf.isDefinedAt).map(oddByHalf)
val oddBalls = sample.collect(oddByHalf)
// Providing "default" values.
val oddsAndEnds = sample.map(n => oddByHalf.applyOrElse(n, (i: Int) => s"[$i]"))
| Note | Optional Functions, PartialFunctions and extractor objects can be converted to each other as shown in the following table.
|
||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Supertypes | |||||||||||||||||
| Known subtypes |
125 types |
||||||||||||||||
| Self type |
Abstract methods
Source
def isDefinedAt(x: A): Boolean
Checks if a value is contained in the function's domain.
| Value parameters |
|
|---|---|
| Returns |
|
Concrete methods
Source
override def andThen[C](k: B => C): PartialFunction[A, C]
Composes this partial function with a transformation function that gets applied to results of this partial function.
If the runtime type of the function is a PartialFunction then the other andThen method is used (note its cautions).
| Type parameters |
|
|---|---|
| Value parameters |
|
| Returns | a partial function with the domain of this partial function, possibly narrowed by the specified function, which maps arguments |
| Definition Classes | Function1 |
Source
Composes this partial function with another partial function that gets applied to results of this partial function.
Note that calling isDefinedAt on the resulting partial function may apply the first partial function and execute its side effect. For efficiency, it is recommended to call applyOrElse instead of isDefinedAt or apply.
| Type parameters |
|
|---|---|
| Value parameters |
|
| Returns | a partial function with the domain of this partial function narrowed by other partial function, which maps arguments |
Source
def applyOrElse[A1 <: A, B1 >: B](x: A1, default: A1 => B1): B1
Applies this partial function to the given argument when it is contained in the function domain. Applies fallback function where this partial function is not defined.
Note that expression pf.applyOrElse(x, default) is equivalent to
if(pf isDefinedAt x) pf(x) else default(x)
except that applyOrElse method can be implemented more efficiently. For all partial function literals the compiler generates an applyOrElse implementation which avoids double evaluation of pattern matchers and guards. This makes applyOrElse the basis for the efficient implementation for many operations and scenarios, such as:
- combining partial functions into orElse/andThen chains does not lead to excessive apply/isDefinedAt evaluation - lift and unlift do not evaluate source functions twice on each invocation - runWith allows efficient imperative-style combining of partial functions with conditionally applied actions
For non-literal partial function classes with nontrivial isDefinedAt method it is recommended to override applyOrElse with custom implementation that avoids double isDefinedAt evaluation. This may result in better performance and more predictable behavior w.r.t. side effects.
| Value parameters |
|
|---|---|
| Returns | the result of this function or fallback function application. |
Source
Composes another partial function k with this partial function so that this partial function gets applied to results of k.
Note that calling isDefinedAt on the resulting partial function may apply the first partial function and execute its side effect. For efficiency, it is recommended to call applyOrElse instead of isDefinedAt or apply.
| Type parameters |
|
|---|---|
| Value parameters |
|
| Returns | a partial function with the domain of other partial function narrowed by this partial function, which maps arguments |
Source
def elementWise: ElementWiseExtractor[A, B]
Returns an extractor object with a unapplySeq method, which extracts each element of a sequence data.
| Example | |
|---|
Source
Turns this partial function into a plain function returning an Option result.
| Returns | a function that takes an argument |
|---|---|
| See also | Function.unlift |
Source
Composes this partial function with a fallback partial function which gets applied where this partial function is not defined.
| Type parameters |
|
|---|---|
| Value parameters |
|
| Returns | a partial function which has as domain the union of the domains of this partial function and |
Source
Composes this partial function with an action function which gets applied to results of this partial function. The action function is invoked only for its side effects; its result is ignored.
Note that expression pf.runWith(action)(x) is equivalent to
if(pf isDefinedAt x) { action(pf(x)); true } else false
except that runWith is implemented via applyOrElse and thus potentially more efficient. Using runWith avoids double evaluation of pattern matchers and guards for partial function literals.
| Value parameters |
|
|---|---|
| Returns | a function which maps arguments |
| See also |
|
Source
Tries to extract a B from an A in a pattern matching expression.
Inherited methods
Source
def apply(v1: A): R
Apply the body of this function to the argument.
| Returns | the result of function application. |
|---|---|
| Inherited from | Function1 |
Source
def compose[A](g: A => A): A => R
Composes two instances of Function1 in a new Function1, with this function applied last.
| Type parameters |
|
|---|---|
| Value parameters |
|
| Returns | a new function |
| Inherited from | Function1 |
Source
Returns a string representation of the object.
The default representation is platform dependent.
| Returns | a string representation of the object. |
|---|---|
| Definition Classes | Function1 -> Any |
| Inherited from | Function1 |
© 2002-2022 EPFL, with contributions from Lightbend.
Licensed under the Apache License, Version 2.0.
https://scala-lang.org/api/3.2.0/scala/PartialFunction.html