# Scala PartialFunction

2021-10-22 10:44:00

`PartialFunction` yes Scala Another interesting function , Also very useful .
One `PartialFunction[A, B]` A function of type is a unary function , Receive a type of A Parameters of , The return type is B Value . however X The value range of can not cover A The entire range of values , You can only cover part of the value field . among `isDefinedAt` You can test whether a value falls on the defined parameter value field .

In simple vernacular , It's just one. `PartialFunction` Only a subset of parameters is processed .

Even for a:A call `isDefinedAt` return true, call `apply(a)` You may also throw an exception , such as ：

And `scala.Function1` The difference is ,`PartialFunction` You can choose to do some operations that are not in the parameter value field .
such as ：

`isEven` The parameter range of is even , and `isOdd` Odd number . `(isEven orElse isOdd).apply(1)` You can handle both even and odd numbers , It's equivalent to combining two partial functions .

It contains other methods ：

• `andThen`: Further processing of the results ,isEven.andThen(println)(2)
• `applyOrElse`: isEven.applyOrElse(1,isOdd)
• `compose`: and `andThen` similar , But call the last one first , Call the first one again .isEven.compose((x:Int) => x+2)(2) //4
• `lift`: Convert to a normal function ,isEven.lift(2), return Option
• `orElse`: Combine , Expand the range of parameters
• `runWith`:isEven.runWith(println)(2). Equivalent if(pf isDefinedAt x) { action(pf(x)); true } else false. The return result type is (A) ⇒ Boolean, This sum `andThen` Different ,`andThen` return `PartialFunction[A, C]`

https://chowdera.com/2021/10/20211009000611634w.html