现在我有一个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
}
...
}