概念
在Scala中,偏函数是具有类型PartialFunction[-T,+V]的一种函数。T是其接受的函数类型,V是其返回的结果类型。
目的
可以用于模式匹配,从而搞定一些比如说只处理集合的部分元素
给你一个集合val list = List(1, 2, 3, 4, “abc”) ,请完成如下要求:
将集合list中的所有数字+1,并返回一个新的集合
要求忽略掉 非数字 的元素,即返回的 新的集合 形式为 (2, 3, 4, 5)
用法
object TestParti {
def main(args: Array[String]): Unit = {
val list = List(1, 2, 3, 4, "abc")
val list2 = list.collect(f1)
print(list2) //List(2, 3, 4, 5)
}
def f1: PartialFunction[Any, Int] = {
case x: Int => x + 1
}
}