现在我有一个RealVector
班级和ComplexVector
班级。它们的逻辑几乎相同,所以我想将它们组合成一个Vector
类。RealVector
需要一个List[Double]
而ComplexVector
需要一个List[ComplexNumber]
whereComplexNumber
是我创建的一个案例类。
我如何使它case class Vector
接受这两种List
类型中的任何一种?请注意,虽然大多数方法的代码是相同的,但其中一些可能会返回 aDouble
或ComplexNumber
取决于List
类型。在这种情况下使用案例类是否正确,或者我应该使用普通类?
编辑:我当前的代码
trait VectorElement[A]
implicit object RealVectorElement extends VectorElement[Double]
implicit object ComplexVectorElement extends VectorElement[ComplexNumber]
case class MyVector[A: VectorElement](components: List[A]) {
def +(that:MyVector[A]):MyVector[A] = {
if (this.dimension != that.dimension) throw new Exception("Cannot add MyVectors of different dimensions.");
new MyVector((this.components zip that.components).map(c => c._1 + c._2));
}
def -(that:MyVector[A]):MyVector[A] = {
if (this.dimension != that.dimension) throw new Exception("Cannot subtract MyVectors of different dimensions.");
new MyVector((this.components zip that.components).map(c => c._1 - c._2)); // ERROR HERE: error: value - is not a member of type parameter A
}
...
}