按类型过滤集合的最佳方法是什么?

frh*_*ack 2 scala

按类型过滤集合的最佳方法是什么? 我希望结果类型是过滤类型. 我找到了两种可能的语法,哪种更好?

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)

pam*_*amu 5

运用 collect

list.collect {
  case a: Int => a
}
Run Code Online (Sandbox Code Playgroud)