【问题标题】:Scala : Collect with genericsScala:使用泛型收集
【发布时间】:2017-06-28 08:31:00
【问题描述】:

鉴于以下情况

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 => icase s: String => s。有没有办法让它更紧凑?谢谢

【问题讨论】:

    标签: scala generics partialfunction


    【解决方案1】:
    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

    【讨论】:

    • 这是我遵循的方法,但添加了以下 def itemsAs[T <: MyInterface](implicit tag: ClassTag[T]): 以便输入它并且不允许提供每个参数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    相关资源
    最近更新 更多