Scala Partial Function从官方文档解析

A partial function of type PartialFunction[A, B] is a unary function where the domain does not necessarily include all values of type A.

一个PartialFunction[A, B]类型的偏函数是一个一元函数。它的输入值的范围并不包含所有A类型的值。

The function isDefinedAtallows to test dynamically if a value is in the domain of the function.

给定一个A类型的值,isDefinedAt函数可以用来动态地检测这个值是否属于此偏函数的输入范围。

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 }

如果有一个a: A,虽然isDefinedAt返回true,但apply(A)可能会返回一个异常。

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.

调用者有责任在调用apply之前先调用isDefinedAt来做检查。因为如果isDefinedAt返回了false,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:

偏函数和Function1的区别是,偏函数的用户可以选择对输入域以外的输入值做一些特殊的处理。

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)
原文地址:https://www.cnblogs.com/shuada/p/5039133.html