若是你想定义一个函数,而让它只接受和处理其参数定义域范围内的子集,对于这个参数范围外的参数则抛出异常,这样的函数就是偏函数(顾名思异就是这个函数只处理传入来的部分参数)。java
def isDefinedAt(x: A): Boolean //做用是判断传入来的参数是否在这个偏函数所处理的范围内
scala> val divide = (x : Int) => 100/x divide: Int => Int = <function1> 输入参数0 scala> divide(0) java.lang.ArithmeticException: / by zero
val divide = new PartialFunction[Int,Int] { def isDefinedAt(x: Int): Boolean = x != 0 //判断x是否等于0,当x = 0时抛出异常 def apply(x: Int): Int = 100/x }
val divide1 : PartialFunction[Int,Int] = { case d : Int if d != 0 => 100/d //功能和上面的代码同样,这就是偏函数的强大之处,方便,简洁!! }
scala> divide1.isDefinedAt(0) res1: Boolean = false scala> divide1.isDefinedAt(10) res2: Boolean = true
val rs : PartialFunction[Int , String] = { case 1 => "One" case 2 => "Two" case _ => "Other" }
scala> rs(1) res4: String = One scala> rs(2) res5: String = Two scala> rs(100) res6: String = Other
scala> val or1 : PartialFunction[Int,String] = {case 1 => "One"} or1: PartialFunction[Int,String] = <function1> scala> val or2 : PartialFunction[Int,String] = {case 2 => "Two"} or2: PartialFunction[Int,String] = <function1> scala> val or_ : PartialFunction[Int,String] = {case _ => "Other"} or_: PartialFunction[Int,String] = <function1> scala> val or = or1 orElse or2 orElse or_ //使用orElse将多个偏结合起来 or: PartialFunction[Int,String] = <function1> scala> or(1) res7: String = One scala> or(20) res9: String = Other
scala> val orCase:(Int => String) = or1 orElse {case _ => "Other"} orCase: Int => String = <function1> scala> orCase(1) res10: String = One scala> orCase(10) res11: String = Other
scala> val at1 : PartialFunction[Int,String] = {case cs if cs == 1 => "One"} at1: PartialFunction[Int,String] = <function1> scala> val at2 : PartialFunction[String,String] = {case cs if cs eq "One" => "The num is 1"} at2: PartialFunction[String,String] = <function1> scala> val num = at1 andThen at2 num: PartialFunction[Int,String] = <function1> scala> num(1) res18: String = The num is 1