我认为标题很困惑,所以我只展示一些代码:
open class Polygon {
open val vertices: List<Point>
constructor(vertices: List<Point>) {
this.vertices = vertices.toList()
class Face: Polygon {
override val vertices: List<Vertex>
其中Vertex
是Point
的子类型。
Intellij IDEA 检查在 Polygon 的构造函数中显示此警告:
是否有更正确的方法来实现 Polygon
- Face
层次结构,其中 vertices
为 Vertex
类型列表code> 在派生类 Face
中?
最佳答案
使用泛型类型
open class Polygon {
open val vertices: List<Point>
constructor(vertices: List<Point>) {
this.vertices = vertices.toList()
class Face: Polygon {
override val vertices: List<Vertex>
您可以使 Polygon 有一个通用参数:
open class Polygon<T: Point> {
open val vertices: List<T>
constructor(vertices: List<T>) {
this.vertices = vertices.toList()
}
}
class Face(vertices: List<Vertex>): Polygon<Vertex>(vertices)
这样就不需要重新定义字段,从而减少了重复。
使用主构造函数
您可以像这样进一步清理代码:
open class Polygon<T: Point>(val vertices: List<T>)
class Face(vertices: List<Vertex>): Polygon<Vertex>(vertices)
关于oop - Kotlin:如何将作为集合的类变量重写为子类型的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49162835/