基本上我想做这样的事情:
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
Run Code Online (Sandbox Code Playgroud)
我已经在这个问题上看到了一些不同的想法,但是它们似乎都不适合这种情况 - 因为它们似乎不允许我在其他地方编写代码,这些代码myShape.getCoords就好像它已经在Shape子类中正确定义,返回来自子类的对象列表CoordSystem.
我还在Scala Lang电子邮件列表中找到了一个关于泛型的有趣讨论,但无法将其与我的情况联系起来.
任何帮助感激不尽!
这样的事情怎么样:
class CoordSystem
class C3D(val x: Double, y: Double, z: Double) extends CoordSystem
class C2D(val x: Double, y: Double) extends CoordSystem
trait ShapeLike[+C <: CoordSystem] {
def getCoords: List[C]
}
abstract class Shape extends ShapeLike[CoordSystem]
class Pyramid extends Shape with ShapeLike[C3D] {
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))
}
Run Code Online (Sandbox Code Playgroud)
当然,没有什么可以强迫你声明额外的类型ShapeLike来做到这一点; 它的目的是允许您使用该类型Shape而不会烦恼额外的类型参数.
所以,实际上标题中所述问题的答案是:如果在超类中定义为协变类型参数,则可以"收紧"子类中类型参数的类型边界; 相反,您可以"松开"逆变型参数的类型边界.
| 归档时间: |
|
| 查看次数: |
181 次 |
| 最近记录: |