scala

# 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 }

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)

Self Type
  PartialFunction[A, B]
Source
  PartialFunction.scala
Version

  1.0, 16/07/2003

Linear Supertypes
(A) ⇒ B, AnyRef, Any
Known Subclasses
::, AbstractBuffer, AbstractMap, AbstractMap, AbstractMap, AbstractPartialFunction, AbstractSeq, AbstractSeq, AnyRefMap, Appended, Appended, ArrayBuffer, ArraySeq, ArrayStack, Buffer, BufferProxy, Cons, DefaultMap, DefaultMap, DefaultMapModel, DoubleLinkedList, DroppedWhile, DroppedWhile, DroppedWhile, Empty, EmptyView, EmptyView, Exclusive, Filtered, Filtered, Filtered, FilteredKeys, FilteredKeys, FlatMapped, FlatMapped, Forced, Forced, HashMap, HashMap, HashMap1, HashTrieMap, ImmutableMapAdaptor, Impl, Inclusive, Inclusive, IndexedSeq, IndexedSeq, IndexedSeq, IndexedSeqView, IntMap, LinearSeq, LinearSeq, LinearSeq, LinkedHashMap, LinkedList, List, ListBuffer, ListMap, ListMap, LongMap, LongMap, Map, Map, Map, Map, Map1, Map2, Map3, Map4, MapLike, MapLike, MapLike, MapProxy, MapProxy, MapProxy, MapProxyLike, Mapped, Mapped, MappedValues, MappedValues, MultiMap, MutableList, Nil, Node, NumericRange, ObservableBuffer, ObservableMap, OpenHashMap, PagedSeq, Patched, Patched, Prepended, Prepended, Queue, Queue, QueueProxy, Range, ResizableArray, Reversed, Reversed, Reversed, Script, Seq, Seq, Seq, SeqForwarder, SeqProxy, SeqView, SeqViewLike, Sliced, Sliced, Sliced, SortedMap, SortedMap, SortedMapLike, Stack, Stack, StackProxy, Stream, StreamView, StreamViewLike, StringBuilder, SynchronizedBuffer, SynchronizedMap, SynchronizedQueue, SynchronizedStack, SystemProperties, TakenWhile, TakenWhile, TakenWhile, Transformed, Transformed, Transformed, TreeMap, TrieMap, UnrolledBuffer, Vector, WithDefault, WithDefault, WithDefault, WrappedArray, WrappedString, Zipped, Zipped, ZippedAll, ZippedAll, ofBoolean, ofByte, ofChar, ofDouble, ofFloat, ofInt, ofLong, ofRef, ofShort, ofUnit
Type Hierarchy Learn more about scaladoc diagrams
Ordering

1. Alphabetic
2. By inheritance

Inherited

1. PartialFunction
2. Function1
3. AnyRef
4. Any

Implicitly

1. by any2stringadd
2. by StringFormat
3. by Ensuring
4. by ArrowAssoc

1. Hide All
2. Show all

Learn more about member selection
Visibility

1. Public
2. All

### Abstract Value Members

1. #### abstract 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.

   Definition Classes
     Function1

2. #### abstract def isDefinedAt(x: A): Boolean

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

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

   x

     the value to test

   returns

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

### Concrete Value Members

1. #### final def !=(arg0: Any): Boolean

   Definition Classes
     AnyRef → Any

2. #### final def ##(): Int

   Definition Classes
     AnyRef → Any

3. #### def +(other: String): String

   Implicit information
     This member is added by an implicit conversion from PartialFunction[A, B] to any2stringadd[PartialFunction[A, B]] performed by method any2stringadd in scala.Predef.
   Definition Classes
     any2stringadd

4. #### def ->[B](y: B): (PartialFunction[A, B], B)

   Implicit information
     This member is added by an implicit conversion from PartialFunction[A, B] to ArrowAssoc[PartialFunction[A, B]] performed by method ArrowAssoc in scala.Predef.
   Definition Classes
     ArrowAssoc
   Annotations
     @inline()

5. #### final def ==(arg0: Any): Boolean

   Definition Classes
     AnyRef → Any

6. #### 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.

   C

     the result type of the transformation function.

   k

     the transformation function

   returns

     a partial function with the same domain as this partial function, which maps arguments `x` to `k(this(x))`.

   Definition Classes
     PartialFunction → Function1

7. #### 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.

   x

     the function argument

   default

     the fallback function

   returns

     the result of this function or fallback function application.

   Since

     2.10

8. #### final def asInstanceOf[T0]: T0

   Definition Classes
     Any

9. #### def clone(): AnyRef

   Attributes
     protected[java.lang]
   Definition Classes
     AnyRef
   Annotations
     @throws( ... )

10. #### 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.

    A

      the type to which function `g` can be applied

    g

      a function A => T1

    returns

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

    Definition Classes
      Function1
    Annotations
      @unspecialized()

11. #### def ensuring(cond: (PartialFunction[A, B]) ⇒ Boolean, msg: ⇒ Any): PartialFunction[A, B]

    Implicit information
      This member is added by an implicit conversion from PartialFunction[A, B] to Ensuring[PartialFunction[A, B]] performed by method Ensuring in scala.Predef.
    Definition Classes
      Ensuring

12. #### def ensuring(cond: (PartialFunction[A, B]) ⇒ Boolean): PartialFunction[A, B]

    Implicit information
      This member is added by an implicit conversion from PartialFunction[A, B] to Ensuring[PartialFunction[A, B]] performed by method Ensuring in scala.Predef.
    Definition Classes
      Ensuring

13. #### def ensuring(cond: Boolean, msg: ⇒ Any): PartialFunction[A, B]

    Implicit information
      This member is added by an implicit conversion from PartialFunction[A, B] to Ensuring[PartialFunction[A, B]] performed by method Ensuring in scala.Predef.
    Definition Classes
      Ensuring

14. #### def ensuring(cond: Boolean): PartialFunction[A, B]

    Implicit information
      This member is added by an implicit conversion from PartialFunction[A, B] to Ensuring[PartialFunction[A, B]] performed by method Ensuring in scala.Predef.
    Definition Classes
      Ensuring

15. #### final def eq(arg0: AnyRef): Boolean

    Definition Classes
      AnyRef

16. #### def equals(arg0: Any): Boolean

    Definition Classes
      AnyRef → Any

17. #### def finalize(): Unit

    Attributes
      protected[java.lang]
    Definition Classes
      AnyRef
    Annotations
      @throws( classOf[java.lang.Throwable] )

18. #### def formatted(fmtstr: String): String

    Returns string formatted according to given `format` string.

    Returns string formatted according to given `format` string. Format strings are as for `String.format` (@see java.lang.String.format).

    Implicit information
      This member is added by an implicit conversion from PartialFunction[A, B] to StringFormat[PartialFunction[A, B]] performed by method StringFormat in scala.Predef.
    Definition Classes
      StringFormat
    Annotations
      @inline()

19. #### final def getClass(): Class[_]

    Definition Classes
      AnyRef → Any

20. #### def hashCode(): Int

    Definition Classes
      AnyRef → Any

21. #### final def isInstanceOf[T0]: Boolean

    Definition Classes
      Any

22. #### 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

23. #### final def ne(arg0: AnyRef): Boolean

    Definition Classes
      AnyRef

24. #### final def notify(): Unit

    Definition Classes
      AnyRef

25. #### final def notifyAll(): Unit

    Definition Classes
      AnyRef

26. #### 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.

    A1

      the argument type of the fallback function

    B1

      the result type of the fallback function

    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.

27. #### 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.

    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.

    Since

      2.10

    See also

      `applyOrElse`.

28. #### final def synchronized[T0](arg0: ⇒ T0): T0

    Definition Classes
      AnyRef

29. #### def toString(): String

    Definition Classes
      Function1 → AnyRef → Any

30. #### final def wait(): Unit

    Definition Classes
      AnyRef
    Annotations
      @throws( ... )

31. #### final def wait(arg0: Long, arg1: Int): Unit

    Definition Classes
      AnyRef
    Annotations
      @throws( ... )

32. #### final def wait(arg0: Long): Unit

    Definition Classes
      AnyRef
    Annotations
      @throws( ... )

33. #### def →[B](y: B): (PartialFunction[A, B], B)

    Implicit information
      This member is added by an implicit conversion from PartialFunction[A, B] to ArrowAssoc[PartialFunction[A, B]] performed by method ArrowAssoc in scala.Predef.
    Definition Classes
      ArrowAssoc

### Inherited from (A) ⇒ B

### Inherited from AnyRef

### Inherited from Any

### Inherited by implicit conversion any2stringadd from PartialFunction[A, B] to any2stringadd[PartialFunction[A, B]]

### Inherited by implicit conversion StringFormat from PartialFunction[A, B] to StringFormat[PartialFunction[A, B]]

### Inherited by implicit conversion Ensuring from PartialFunction[A, B] to Ensuring[PartialFunction[A, B]]

### Inherited by implicit conversion ArrowAssoc from PartialFunction[A, B] to ArrowAssoc[PartialFunction[A, B]]

### Ungrouped