从通用集合中选择类型的子集
好吧,伙计们,我现在开始学习一些 scala,但是时不时地,一些更棘手的概念让我困惑。让我向您介绍水果世界:
class Fruit
class Pear extends Fruit
class Apple extends Fruit
class GrannySmith extends Apple
现在,如果我想要一个新的通用集合,允许我从通用集合中挑选水果子集,该怎么办?幼稚的实现:
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 时给出了这个:
<console>:8: warning: abstract type U in type pattern U is unchecked since it is eliminated by erasure
case u:U => true
所以我对类型擦除的理解非常模糊。我知道它在某种程度上与 jvm 中有限的动态类型有关,并且您有时可以使用清单来解决它,正如 Daniel 正在谈论 此处。我特别不明白的是,在这个例子中它是如何工作的,以及如何绕过它。
我很感谢任何帮助!
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
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
})
}
This does not work however.
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)
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
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个怎么样?您甚至可以获得正确的返回类型。
How about this? You even get the right return type.