【发布时间】:2015-03-22 04:32:30
【问题描述】:
我知道存在很多关于泛型类型的类型擦除和模式匹配的问题,但我无法从这些问题的答案中理解在我的情况下我应该做什么,我无法在标题中更好地解释它。
以下代码片段被简化以展示我的案例。
所以我有一个特质
trait Feature[T] {
value T
def sub(other: Feature[T]): Double
}
// implicits for int,float,double etc to Feature with sub mapped to - function
...
那我有课
class Data(val features: IndexedSeq[Feature[_]]) {
def sub(other: Data): IndexedSeq[Double] = {
features.zip(other.features).map {
case(e1: Feature[t], e2: Feature[y]) => e1 sub e2.asInstanceOf[Feature[t]]
}
}
}
我有一个这样的测试用例
case class TestFeature(val value: String) extends Feature[String] {
def sub(other: Feature[String]): Double = value.length - other.length
}
val testData1 = new Data(IndexedSeq(8, 8.3f, 8.232d, TestFeature("abcd"))
val testData2 = new Data(IndexedSeq(10, 10.1f, 10.123d, TestFeature("efg"))
testData1.sub(testData2).zipWithIndex.foreach {
case (res, 0) => res should be (8 - 10)
case (res, 1) => res should be (8.3f - 10.1f)
case (res, 2) => res should be (8.232d - 10.123d)
case (res, 3) => res should be (1)
}
这在某种程度上有效。如果我尝试对Data 的实例进行子操作,这些实例在features 的同一索引中具有不同的类型,我会得到ClassCastException。这实际上满足了我的要求,但如果可能的话,我想使用 Option 而不是抛出异常。我怎样才能使下面的代码工作?
class Data(val features: IndexedSeq[Feature[_]]) {
def sub(other: Data): IndexedSeq[Double] = {
features.zip(other.features).map {
// of course this does not work, just to give idea
case(e1: Feature[t], e2: Feature[y]) if t == y => e1 sub e2.asInstanceOf[Feature[t]]
}
}
}
另外我在 Scala 方面真的很缺乏经验,所以我想获得有关这种结构的反馈。还有其他方法可以做到这一点,哪种方法最有意义?
【问题讨论】:
标签: scala generics pattern-matching traits