
上QQ阅读APP看书,第一时间看更新
Partial functions
A partial function is a function that does not provide a result for every possible input value it can be given. It supports only a subset of possible inputs.
In Scala, we can use scala.PartialFunction to define partial functions.
In Scala source code, PartialFunction is defined as follows:
trait PartialFunction[-A, +B] extends (A) ⇒ B
Consider the following example:
scala> val numRange = 1 to 5 numRange: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5) scala> val isEven: PartialFunction[Int, String] = { | case num if num % 2 == 0 => num +" is even" | } isEven: PartialFunction[Int,String] = <function1> scala> val evenNumbers = numRange collect isEven evenNumbers: scala.collection.immutable.IndexedSeq[String] = Vector(2 is even, 4 is even)