【发布时间】:2011-08-16 08:22:42
【问题描述】:
在我的previous question 之后,得到了一个快速而出色的答案,但结果证明我的示例与我的实际生产代码不够匹配。总之,我需要一个新的 collect 方法实现。
第二个水果世界(有一些非常时髦的果树):
class Fruit {
var seeds:Array[Fruit] = Array()
def naiveCollect[F <: Fruit]:Array[Fruit] = this match {
case f:F => Array(this)
case _ => seeds.map(_.select[F]).flatten.toArray
}
}
class Apple extends Fruit
class Pear extends Fruit
class GrannySmith extends Apple
由于类型擦除而无法工作:
var tree = new Fruit { seeds = Array(
new Apple,
new Pear,
new GrannySmith,
new Pear { seeds = Array(
new Apple,
new Pear)},
new Apple)}
scala> tree.naiveCollect[Apple]
res1: Array[Fruit] = Array($anon$2@5a4b99fa)
// wanted output: Apple, GrannySmith, Apple, Apple
编辑,解决方案 1:
事实证明,我设法通过使用 PartialFunction 像在 std lib 中一样生成了一些东西。
class Fruit {
...
def clumsyCollect[F](pf:PartialFunction[Fruit, F]):Seq[F] =
if (pf.isDefinedAt(this))
List(pf(this))
else
seeds.flatMap(_.selectPartial[F](pf))
}
用例:
tree.clumsyCollect { case a:Apple => a }
不过,任何关于清理此问题的替代方案或提示仍然很棒!
【问题讨论】:
标签: generics scala collections type-erasure