scala之偏函数 partial function
0 偏函数简介
偏函数只能通过collect方法来调用,而不能使用map()
-
使用构建特质的实现类(使用的方式是PartialFunction的匿名子类)
-
PartialFunction 是个特质(看源码)
-
构建偏函数时,参数形式 [Any, Int]是泛型,第一个表示参数类型,第二个表示返回参数
-
当使用偏函数时,会遍历集合的所有元素,编译器执行流程时先执行isDefinedAt()如果为true ,就会执行 apply, 构建一个新的Int 对象返回
-
执行isDefinedAt() 为false 就过滤掉这个元素,即不构建新的Int对象.
-
map函数不支持偏函数,因为map底层的机制就是所有循环遍历,无法过滤处理原来集合的元素
-
collect函数支持偏函数
偏函数的定义方式有3种
1 通过val pf = new PartialFunction[In,Out]{}
实现方法来定义偏函数
//方式三 偏函数,其中Any是输入类型、Int是输出类型
val partialFunc: PartialFunction[Any, Int] = new PartialFunction[Any, Int] {
override def isDefinedAt(x: Any): Boolean = {
println(x)
x.isInstanceOf[Int]
}
override def apply(v1: Any): Int = {
println(v1)
v1.asInstanceOf[Int] * 2
}
}
//通过collect函数来调用偏函数,而不能通过map
val list4: List[Int] = list.collect(partialFunc)
println(list4) // List(2, 4, 6, 8, 10)
2 通过简化版的def pf:PartialFunction[In,Out] = {}
定义偏函数
// 4 偏函数的简写,执行顺序 => 遍历List => isDefinedAs() => apply构建Int对象 => *2
def pf: PartialFunction[Any, Int] = {
case a: Int => a * 2
case b: Double => b.toInt * 2
}
val list5: List[Int] = list.collect(pf)
println(list5) //List(2, 4, 6, 8, 10)
3 匿名偏函数
list.collect{
case a:Int =>
case b:Double =>
case c:String =>
}
4 偏函数使用案例
package com.shufang.funs
/**
* 本main方法主要介绍偏函数的入门
*/
object PartitialFunctionDemo {
def main(args: Array[String]): Unit = {
// TODO 需要将List的所有元素*2 ,忽略掉 String类型的元素,并返回一个新的集合
//方式一 filter 结合 map高阶函数的使用
val list = List(1, 2, 3, 4, 5, "string")
val list2: List[Int] = list.filter(a => a.isInstanceOf[Int]).map(_.asInstanceOf[Int]).map(_ * 2)
println(list2) //List(2, 4, 6, 8, 10)
//方式二 通过map + match case
def myfilter(a: Any): Any = {
a match {
case a: Int => a * 2
case _ =>
}
}
val list3: List[Any] = list.map(myfilter)
println(list3) //List(2, 4, 6, 8, 10, ())
//方式三 偏函数,其中Any是输入类型、Int是输出类型
val partialFunc: PartialFunction[Any, Int] = new PartialFunction[Any, Int] {
override def isDefinedAt(x: Any): Boolean = {
println(x)
x.isInstanceOf[Int]
}
override def apply(v1: Any): Int = {
println(v1)
v1.asInstanceOf[Int] * 2
}
}
//通过collect函数来调用偏函数,而不能通过map
val list4: List[Int] = list.collect(partialFunc)
println(list4) // List(2, 4, 6, 8, 10)
// 4 偏函数的简写,执行顺序 => 遍历List => isDefinedAs() => apply构建Int对象 => *2
def pf: PartialFunction[Any, Int] = {
case a: Int => a * 2
case b: Double => b.toInt * 2
}
val list5: List[Int] = list.collect(pf)
println(list5) //List(2, 4, 6, 8, 10)
}
}