按类型过滤集合的最佳方法是什么? 我希望结果类型是过滤类型. 我找到了两种可能的语法,哪种更好?
val list = List(1,"two",3,"four")
//1) using "Typed" helper object
object Typed { def unapply[A](a: A) = Some(a) }
val list1 = for {
Typed(i: Int) <- list
} yield i
//2) using flatMap
val list2 = lo.flatMap {
case i: Int => List(i)
case _ => Nil
}
Run Code Online (Sandbox Code Playgroud) scala ×1