代码之家  ›  专栏  ›  技术社区  ›  Bruno

Scala:使用泛型收集

  •  3
  • Bruno  · 技术社区  · 7 年前

    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 .有没有办法让它更紧凑?谢谢

    1 回复  |  直到 7 年前
        1
  •  5
  •   dveim    7 年前
    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