object PartFun {
def main(args: Array[String]): Unit = {
val ls: List[Any] = List("wnn","a","b",1,2,3,10.0,11.0,true)
val f: PartialFunction[Any, Int] =new PartialFunction[Any,Int] {
override def isDefinedAt(x: Any): Boolean = {
x.isInstanceOf[Int]
}
override def apply(v1: Any): Int = {
v1.asInstanceOf[Int]*100
}
}
//collect支持偏函数
val res: List[Int] =ls.collect(f)
println(res)
/*List(100, 200, 300)*/
}
}
偏函数简写
object PartFun2 {
//偏函数简写
def f:PartialFunction[Any,String]={
case x :String=>x.toUpperCase
}
val ff: PartialFunction[Any, Int] =new PartialFunction[Any,Int] {
override def isDefinedAt(x: Any): Boolean = {
x.isInstanceOf[Int]
}
override def apply(v1: Any): Int = {
v1.asInstanceOf[Int]*100
}
}
}
364

被折叠的 条评论
为什么被折叠?



