偏函数的英文是Partial Function(部分函数),从这名字来看很容易理解为函数没有定义完,有哪些情况是函数没有定义完?
函数没有定义完太常见了,因为我们有可能是不知道全部的业务逻辑的,所以偏函数是非常常见的
之前说过,Scala的函数背后都是类,例如会有:
trait Function1
而且没有实现函数式编程的时候,需要实现接口,然后调对应的方法,但是现在不用了,其实是Scala帮我们写了!!!
其实可以发现Scala的Function和Spark的Function是不一样的
至于偏函数背后也是一个类,trait PartialFunction[-A, +B]
其实可以这样理解:
{
case Hello(name,content,sender) =>
println("Hello,"+name+":" + content)
counter += 1
Thread.sleep(1000)
sender ! HelloBack(name,content+counter,this)
}
在这个函数中会处理不同的消息,但是没有定义完所有的类型,
它会通过isDefinedAt会判断你的值是否在域中,
如果isDefinedAt返回true的,就会调用apply(a)方法
其实是就是调用apply方法的时候把值传进来,然后进行case匹配
Partial Function 的例子:
package com.dt.spark.scala.basics
object HelloPartialFunction {
def main(args:Array[String]){
val sample = 1 to 10
val isEven:PartialFunction[Int,String] ={
case x if x % 2==0 => x+" is even"
}
// isEven(3) // Match Error
isEven(2)
val evenNumbers = sample.collect(isEven)
evenNumbers.foreach(println)
val isOld:PartialFunction[Int,String] ={
case x if x % 2==1 => x+" is old"
}
val numbers=sample.map(isEven orElse isOld)
numbers.foreach(println)
}
}
归纳总结:1.偏函数的定义以及为什么它会出现?
2.函数的背后,偏函数的背后
3.例子