基本上我想要做这样的事情:我可以使用Scala抽象方法绑定的类型,然后“收紧”子类中的定义吗?
class Shape
class CoordSystem
class C3D(val x: Double, y: Double, z: Double) extends CoordSystem
class C2D(val x: Double, y: Double) extends CoordSystem
abstract class Shape {
def getCoords[C <: CoordSystem]: List[C]
}
class Pyramid extends Shape {
def getCoords: List[C3D] =
List(new C3D(1,2,1), new C3D(1,1,1), new C3D(2,2,1), new C3D(2,1,1), new C3D(1.5,1.5,3))
}
>> error: class Pyramid needs to be abstract, since method getCoords in class Shape of type [C <: CoordSystem]List[C] is not defined
我已经看到了不同的想法上this answer了一把,但没有人似乎对这种情况相当正确的 - 因为他们似乎并没有让我在其他地方编写代码,其引用myShape.getCoords
就好像它已在Shape
子类中正确定义,返回CoordSystem
的子类中的对象列表。
我还在Scala Lang的电子邮件列表中发现了an interesting discussion about generics,但无法将其与我的情况紧密结合。
感谢任何帮助!
非常感谢让 - 菲利普 - 这就像一个魅力! –