偏函数(
- 偏函数是只对函数定义域的一个子集进行定义的函数。 scala中用scala.PartialFunction[-T, +S]类来表示
)
Scala提供了定义偏函数(PartialFunction)的语法快捷:
val pf: PartialFunction[Int, String] = {
case i if i%2 == 0 => "even"
}
它们也可能由 orElse 组成:
val tf: (Int => String) = pf orElse { case _ => "odd"}
tf(1) == "odd"
tf(2) == "even"
偏函数出现在很多场景,并被有效的编码为 PartialFunction,例如 方法参数:
trait Publisher[T] {
def subscribe(f: PartialFunction[T, Unit])
}
val publisher: Publisher[Int] = ..
publisher.subscribe {
case i if isPrime(i) => println("found prime", i)
case i if i%2 == 0 => count += 2
/* ignore the rest */
}
或在返回一个Option的情况下:
// Attempt to classify the the throwable for logging.
type Classifier = Throwable => Option[java.util.logging.Level]
可以更好的用PartialFunction表达
type Classifier = PartialFunction[Throwable, java.util.Logging.Level]
</