当前位置:网站首页>Scala之偏函数Partial Function
Scala之偏函数Partial Function
2022-06-27 06:10:00 【YaoYong_BigData】
一、定义
1.被包在花括号内没有match的一组case语句是一个偏函数
2.偏函数是PartialFunction[A, B]的一个实例
- A代表输入参数类型
- B代表返回结果类型
3.偏函数在scala中是一个特质
二、实例
1.需求
给你一个集合 val list = List(1, 2, 3, "a", true) ,请完成如下要求:
将集合list中的所有数字乘以10,并返回一个新的集合
要求忽略掉非数字的元素,即返回的新的集合形式为 (10,20,30)
2.代码
object _06PartialFunction {
def main(args: Array[String]): Unit = {
val list = List(1, 2, 3, "a", true)
//方式1
list.filter(x => x.isInstanceOf[Int]).map(x => x.asInstanceOf[Int] * 10).foreach(println)
println("-" * 60)
//方式2
val list0 = list.collect{
case x:Int => x * 10
}
list0.foreach(println)
println("------list0------")
//方式3:推荐用法
val pf1:PartialFunction[Any, Int] = {
case x:Int => x * 10
}
//collect方法,类似于map方法,collect方法只能传递偏函数
list.collect(pf1).foreach(println)
println("------pf1------")
//方式4
val pf2 = new PartialFunction[Any,Int] {
//只对返回true的时候交给apply处理
override def isDefinedAt(x: Any): Boolean = x.isInstanceOf[Int]
//处理方法
override def apply(v1: Any): Int = v1.asInstanceOf[Int] * 10
}
list.collect(pf2).foreach(println)
println("------pf2------")
//方式5
val pf3 = new PartialFunction[Any, Int] {
override def isDefinedAt(x: Any): Boolean = x match {
case a:Int => true
case _ => false
}
override def apply(v1: Any): Int = v1 match {
case a:Int => a * 10
}
}
list.collect(pf3).foreach(println)
println("------pf3------")
}
}
上述每种方式都会打印:
10
20
30
三、偏函数的小结
1.使用构建特质的实现类(使用的方式是PartialFunction的匿名子类);
2.PartialFunction 是个特质(看源码);
3.构建偏函数时,参数形式 [Any, Int]是泛型,第一个表示参数类型,第二个表示返回参数;
4.当使用偏函数时,会遍历集合的所有元素,编译器执行流程时先执行isDefinedAt()如果为true ,就会执行 apply, 构建一个新的Int 对象返回;
5.执行isDefinedAt() 为false 就过滤掉这个元素,即不构建新的Int对象;
6.map函数不支持偏函数,因为map底层的机制就是所有循环遍历,无法过滤处理原来集合的元素;collect函数支持偏函数。
边栏推荐
猜你喜欢

JVM class loading mechanism

openresty使用文档

Altium Designer 19 器件丝印标号位置批量统一摆放

Free SSH and telnet client putty

Dev++ environment setting C language keyword display color

【QT小作】使用结构体数据生成读写配置文件代码

How to check the frequency of memory and the number of memory slots in CPU-Z?

Kubesphere cluster configuration NFS storage solution - favorite

JVM整体结构解析

KubeSphere 集群配置 NFS 存储解决方案-收藏版
随机推荐
Dev++ 环境设置C语言关键字显示颜色
Software testing year end summary report template
30个单片机常见问题及解决办法!
TiDB 基本功能
建模竞赛-光传送网建模与价值评估
我对于测试团队建设的意见
力扣 179、最大数
JVM tuning ideas
信息系统项目管理师---第七章 项目成本管理
Free SSH and telnet client putty
How win 10 opens the environment variables window
[cultivation system] common regular expressions
日期 数据库日期 字符串 之间互相转换
【QT小作】使用结构体数据生成读写配置文件代码
JVM对象组成和存储
Code is data
JVM整体结构解析
IAR Systems全面支持芯驰科技9系列芯片
Yaml file encryption
Senior [Software Test Engineer] learning route and necessary knowledge points