val items = List("a", "b", "c", 1, 2, 3, false, true) def intItems = items.collect {case i : Int => i} def stringItems = items.collect {case s : String => s}
我尝试了以下方法
def itemsAs[T]: List[T] = items.collect { case item: T => item }
但是
itemsAs[Int]
List[Int]] = List(a, b, c, 1, 2, 3, false, true)
另一种方法是提供 partial function 作为参数,但仍必须复制 case i: Int => i case s: String => s .有没有办法让它更紧凑?谢谢
partial function
case i: Int => i
case s: String => s
val items = List("a", "b", "c", 1, 2, 3, false, true) import scala.reflect.ClassTag def collect[T: ClassTag] = items.collect { case x: T => x } collect[Int] // List(1, 2, 3) collect[String] // List(a, b, c)
看见 http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html