从通用集合中选择类型的子集 [英] Selecting a subset of types from a generic collection

查看:138
本文介绍了从通用集合中选择类型的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我现在开始得到一些scala,但每一个时刻,更棘手的概念让我。让我向您介绍水果世界:

Okay guys, I'm starting to get some scala now, but every now and then the trickier concepts get me. Let me introduce you to the fruit world:

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

现在如果我想要一个新的通用集合,从通用集合中选择水果的子集。 Naive实现:

Now what if I want a new generic collection that allows me to pick subsets of Fruits out of the generic collection. Naive implementation:

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)

控制台警告未检查的错误,重新运行-unchecked在定义MyArray时提供:

The console warned about unchecked errors, rerunning with -unchecked gave this while defining MyArray:

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

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

So my understanding of type erasure is very vague. I know that it is somehow related to the limited dynamic types in the jvm, and that you can sometimes get around it using Manifests as Daniel is talking about here. What I particularly don't understand is how this works in this example, and how one could get around it.

我非常感谢任何帮助!

I'm thankful for any help!

推荐答案

这个怎么样?

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

这篇关于从通用集合中选择类型的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆