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 _ => 1/0 }

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 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
val isEven: PartialFunction[Int, String] = {
  case x if x % 2 == 0 => x+" is even"
}

// the method collect can use isDefinedAt to select which members to collect
val evenNumbers = sample collect isEven

val isOdd: PartialFunction[Int, String] = {
  case x if x % 2 == 1 => x+" is odd"
}

// the method orElse allows chaining another partial function to handle
// input outside the declared domain
val numbers = sample map (isEven orElse isOdd)
Note

Optional Functions, PartialFunctions and extractor objects can be converted to each other as shown in the following table.   | How to convert ... | to a PartialFunction | to an optional Function | to an extractor | | :---: | --- | --- | --- | | from a PartialFunction | Predef.identity | lift | Predef.identity | | from optional Function | Function1.UnliftOps#unlift or Function.unlift | Predef.identity | Function1.UnliftOps#unlift | | from an extractor | { case extractor(x) => x } | extractor.unapply _ | Predef.identity |  

Companion
object
Source
PartialFunction.scala
trait A => B
class Object
trait Matchable
class Any
trait MapOps[K, V, CC, C]
trait Map[K, V]
class AbstractMap[K, V]
class AbstractMap[K, V]
class HashMap[K, V]
class IntMap[T]
class ListMap[K, V]
class LongMap[T]
class Map1[K, V]
class Map2[K, V]
class Map3[K, V]
class Map4[K, V]
class WithDefault[K, V]
class WithDefault[K, V]
class TreeMap[K, V]
class TreeSeqMap[K, V]
class VectorMap[K, V]
class AbstractMap[K, V]
class TrieMap[K, V]
class AnyRefMap[K, V]
class HashMap[K, V]
class LinkedHashMap[K, V]
class ListMap[K, V]
class LongMap[V]
class WithDefault[K, V]
class WithDefault[K, V]
class TreeMap[K, V]
trait DefaultMap[K, V]
trait SeqMap[K, V]
trait SeqMap[K, V]
trait SeqMap[K, V]
trait SortedMap[K, V]
trait SortedMap[K, V]
trait SortedMap[K, V]
trait Map[K, V]
trait Map[K, V]
trait Map[K, V]
trait MultiMap[K, V]
class WeakHashMap[K, V]
trait MapView[K, V]
class Filter[K, V]
class FilterKeys[K, V]
class Id[K, V]
class MapValues[K, V, W]
class TapEach[K, V, U]
trait SortedMapOps[K, V, CC, C]
trait SortedMapOps[K, V, CC, C]
trait SortedMapOps[K, V, CC, C]
trait MapOps[K, V, CC, C]
trait MapOps[K, V, CC, C]
trait Seq[A]
class AbstractSeq[A]
class AbstractSeq[A]
class ArraySeq[A]
class ofBoolean
class ofByte
class ofChar
class ofDouble
class ofFloat
class ofInt
class ofLong
class ofRef[T]
class ofShort
class ofUnit
class LazyList[A]
class List[A]
class ::[A]
object Nil
class Exclusive[T]
class Inclusive[T]
class Queue[A]
class Range
class Exclusive
class Inclusive
class Stream[A]
class Cons[A]
object Empty
class Vector[A]
class AbstractSeq[A]
class ArrayBuffer[A]
class ArrayDeque[A]
class Queue[A]
class Stack[A]
class ListBuffer[A]
class ArraySeq[T]
class ofBoolean
class ofByte
class ofChar
class ofDouble
class ofFloat
class ofInt
class ofLong
class ofRef[T]
class ofShort
class ofUnit
trait IndexedSeq[A]
trait IndexedSeq[A]
trait IndexedSeq[T]
trait LinearSeq[A]
trait LinearSeq[A]
trait Seq[A]
trait Seq[A]
trait Buffer[A]
class Accumulator[A, CC, C]

Value members

Abstract methods

Checks if a value is contained in the function's domain.

Checks if a value is contained in the function's domain.

Value Params
x

the value to test

Returns

true, iff x is in the domain of this function, false otherwise.

Source
PartialFunction.scala

Concrete methods

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.

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 Params
C

the result type of the transformation function.

Value Params
k

the transformation function

Returns

a partial function with the domain of this partial function, possibly narrowed by the specified function, which maps arguments x to k(this(x)).

Definition Classes
Source
PartialFunction.scala

Composes this partial function with another partial function that gets applied to results of this partial function.

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. It is highly recommended to call applyOrElse instead of isDefinedAt / apply for efficiency.

Type Params
C

the result type of the transformation function.

Value Params
k

the transformation function

Returns

a partial function with the domain of this partial function narrowed by other partial function, which maps arguments x to k(this(x)).

Source
PartialFunction.scala
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 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 Params
default

the fallback function

x

the function argument

Returns

the result of this function or fallback function application.

Source
PartialFunction.scala

Composes another partial function k with this partial function so that this partial function gets applied to results of k.

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. It is highly recommended to call applyOrElse instead of isDefinedAt / apply for efficiency.

Type Params
R

the parameter type of the transformation function.

Value Params
k

the transformation function

Returns

a partial function with the domain of other partial function narrowed by this partial function, which maps arguments x to this(k(x)).

Source
PartialFunction.scala

Returns an extractor object with a unapplySeq method, which extracts each element of a sequence data.

Returns an extractor object with a unapplySeq method, which extracts each element of a sequence data.

Example

val firstChar: String => Option[Char] = _.headOption
Seq("foo", "bar", "baz") match {
  case firstChar.unlift.elementWise(c0, c1, c2) =>
    println(s"$c0, $c1, $c2") // Output: f, b, b
}
Source
PartialFunction.scala
def lift: A => Option[B]

Turns this partial function into a plain function returning an Option result.

Turns this partial function into a plain function returning an Option result.

Returns

a function that takes an argument x to Some(this(x)) if this is defined for x, and to None otherwise.

See also

Function.unlift

Source
PartialFunction.scala
def orElse[A1 <: A, B1 >: B](that: PartialFunction[A1, B1]): PartialFunction[A1, B1]

Composes this partial function with a fallback partial function which gets applied where this partial function is not defined.

Composes this partial function with a fallback partial function which gets applied where this partial function is not defined.

Type Params
A1

the argument type of the fallback function

B1

the result type of the fallback function

Value Params
that

the fallback function

Returns

a partial function which has as domain the union of the domains of this partial function and that. The resulting partial function takes x to this(x) where this is defined, and to that(x) where it is not.

Source
PartialFunction.scala
def runWith[U](action: B => U): A => Boolean

Composes this partial function with an action function which gets applied to results of this partial function.

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 Params
action

the action function

Returns

a function which maps arguments x to isDefinedAt(x). The resulting function runs action(this(x)) where this is defined.

See also

applyOrElse.

Source
PartialFunction.scala
def unapply(a: A): Option[B]

Tries to extract a B from an A in a pattern matching expression.

Tries to extract a B from an A in a pattern matching expression.

Source
PartialFunction.scala

Inherited methods

def apply(v1: A): B

Apply the body of this function to the argument.

Apply the body of this function to the argument.

Returns

the result of function application.

Inherited from
Function1
Source
Function1.scala
def compose[A](g: A => A): A => B

Composes two instances of Function1 in a new Function1, with this function applied last.

Composes two instances of Function1 in a new Function1, with this function applied last.

Type Params
A

the type to which function g can be applied

Value Params
g

a function A => T1

Returns

a new function f such that f(x) == apply(g(x))

Inherited from
Function1
Source
Function1.scala
override def toString(): String
Definition Classes
Inherited from
Function1
Source
Function1.scala