当前位置:网站首页>Scala PartialFunction

Scala PartialFunction

2021-10-22 10:44:00 Bird's nest

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 :

       
       
       
1
       
       
       
val f: PartialFunction[Int, Any] = { case _ => 1/ 0 }

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

       
       
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
       
       
       
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)

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]

版权声明
本文为[Bird's nest]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/10/20211009000611634w.html

随机推荐