【问题标题】:Selecting a subset of types from a generic collection从泛型集合中选择类型的子集
【发布时间】:2011-08-15 15:57:50
【问题描述】:

好的,伙计们,我现在开始了解一些 scala,但时不时会遇到更棘手的概念。让我向您介绍水果世界:

class Fruit
class Pear extends Fruit
class Apple extends Fruit
class GrannySmith extends Apple

现在,如果我想要一个新的通用集合,它允许我从通用集合中挑选 Fruits 的子集,该怎么办。幼稚的实现:

class MyArray[T](var a:Array[T]) {
  def select[U <: T] = 
    a.filter(_ match {
      case u:U => true
      case _   => false
    })
}

但这不起作用。

scala> var ma = new MyArray(
                        Array(
                          new Apple, 
                          new Fruit, 
                          new Pear, 
                          new GrannySmith, 
                          new Apple, 
                          new Fruit
                        ))


scala> ma.select[Apple]
res1: Array[Fruit] = Array(Apple@4d815146, Fruit@64fef26a, Pear@1ddd40f3, GrannySmith@28d320d6, Apple@3d10d68a, Fruit@1c751d58)

控制台警告未检查的错误,在定义 MyArray 时使用 -unchecked 重新运行给出了这个:

<console>:8: warning: abstract type U in type pattern U is unchecked since it is eliminated by erasure
             case u:U => true

所以我对类型擦除的理解很模糊。我知道它在某种程度上与 jvm 中有限的动态类型有关,并且有时您可以使用 Manifests 来解决它,因为 Daniel 正在谈论 here。我特别不明白的是它在这个例子中是如何工作的,以及如何绕过它。

感谢您的帮助!

【问题讨论】:

    标签: generics scala collections type-erasure


    【解决方案1】:

    这个怎么样?您甚至可以获得正确的返回类型。

    ma.a.collect { case a: Apple => a }
    

    【讨论】:

    • ...你可以说我在添加实际问题之前不小心发布了 =)
    猜你喜欢
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    相关资源
    最近更新 更多