Scala 偏函数
- 偏函数使用的地方很多,但是大部分情况都是把他当成一个普通函数来使用
object Pattern2 {
def main(args: Array[String]): Unit = {
val list = List(10,20,1,"aa",false)
val f = new PartialFunction[Any,Int] {
//只对返回值是true的那些元素处理,是false的跳过
override def isDefinedAt(x: Any): Boolean = x.isInstanceOf[Int]
//是true的时候,交给apply进行处理
override def apply(v1: Any): Int = v1.asInstanceOf[Int]
}
val a = list.collect(f)
println(a) //输出:List(10, 20, 1)
}
}
也可以使用模式匹配
object Pattern2 {
def main(args: Array[String]): Unit = {
val list = List(10,20,1,"aa",false)
val f = new PartialFunction[Any,Int] {
//只对返回值是true的那些元素处理,是false的跳过
override def isDefinedAt(x: Any): Boolean = x match{
case a: Int => true
case _ => false
}
//是true的时候,交给apply进行处理
override def apply(v1: Any): Int = v1 match{
case a:Int => a
}
}
val a = list.collect(f)
println(a)
}
}
- 用一对大括号括起来的一个或多个case语句就是偏函数
object Pattern3 {
def main(args: Array[String]): Unit = {
val list = List(10,20,1,"aa",false)
val list2 = list.collect({
case a:Int => a
})
println(list2) //输出:List(10, 20, 1)
}
}
- 如果函数的参数是元组的时候,很多时候都喜欢用偏函数
object Pattern4 {
def main(args: Array[String]): Unit = {
val map = Map("a"->97,"b"->98,"c"->99)
// map.foreach(x =>{
// println(x._1)
// println(x._2)
// })
//用来替换上面代码
map.foreach({
case(k,v) => println(k)
})
}
}
object Pattern4 {
def main(args: Array[String]): Unit = {
val list = List(
("a",("b",(1,"c"))),
("aa",("bb",(2,"cc"))))
// println(list.map(_._2._2._1)) //输出:List(1, 2)
//优化上面的代码
val list2 = list.map{
case (a,(b,(c,d))) => c
}
println(list2) //输出:List(1, 2)
}
}
注:
- 当是多个参数不是元组的时候,不要用偏函数
- 当传递的参数是一个且是元组时用偏函数最好
val r = foo((x,y)=> {
x+y
})
println(r)
}
def foo(f:(Int,Int)=>Int) =f(10,20)
val r = foo{
case (x,y) => x+y
}
println(r)
}
def foo(f:((Int,Int))=>Int) =f(10,20) //比上述代码多了个括号