第二个实现有什么问题?
作品:
scala> List(1,2,3).collect{ case i: Int if i % 2 == 0 => i }
res1: List[Int] = List(2)
不:
scala> val evens = PartialFunction[Any, Int]{
| case i: Int if i % 2 == 0 => i
| }
evens: PartialFunction[Any,Int] = <function1>
scala> List(1,2,3).collect{evens}
scala.MatchError: 1 (of class java.lang.Integer)
at $anonfun$1.apply(<console>:7)
at $anonfun$1.apply(<console>:7)
at scala.PartialFunction$$anonfun$apply$1.applyOrElse(PartialFunction.scala:242)
at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:33)
at scala.collection.TraversableLike$$anonfun$collect$1.apply(TraversableLike.scala:278)
at scala.collection.immutable.List.foreach(List.scala:318)
...