偏函式collect
阿新 • • 發佈:2020-08-14
package chapter04 object test09 { def main(args:Array[String]):Unit={ val list = List(1,2,3,4,"abc") val list2: List[AnyVal] = list.map(x => { if (x.isInstanceOf[Int]) { x.asInstanceOf[Int] + 1 } }) println(list2) //List(2, 3, 4, 5, ()) val list3: List[AnyVal] = list2.filter(x=>x.isInstanceOf[Int]) println(list3)//List(2, 3, 4, 5) //TODO MAP def f1(n:Any):Boolean={n.isInstanceOf[Int]} def f2(n:Int):Int={n+1} def f3(n:Any):Int={n.asInstanceOf[Int]} val list4: List[Int] = list.filter(f1).map(f3).map(f2) println(list4) //TODO 偏函式1 val addOne3=new PartialFunction[Any,Int] { //Any引數型別,Int返回值型別def isDefinedAt(any: Any): Boolean = { if(any.isInstanceOf[Int]) true else false } def apply(any:Any)=any.asInstanceOf[Int]+1 } //collect:滿足條件的資料操作,map:對全部資料操作 val list5: List[Int] = list.collect(addOne3) println(list5) //TODO 偏函式2 def f4:PartialFunction[Any,Int]={case i:Int=>i+1 } val list6: List[Int] = list.collect(f4) println(list6) //TODO 偏函式3 val list7: List[Int] = list.collect{case i:Int=>i+1} println(list7) } }