oop - Kotlin:如何将作为集合的类变量重写为子类型的集合

标签 oop kotlin

我认为标题很困惑,所以我只展示一些代码:

open class Polygon {
   open val vertices: List<Point>
   constructor(vertices: List<Point>) {
      this.vertices = vertices.toList()

class Face: Polygon {
   override val vertices: List<Vertex>

其中VertexPoint的子类型。

Intellij IDEA 检查在 Polygon 的构造函数中显示此警告:

https://i.imgur.com/W2ItVRn.png

是否有更正确的方法来实现 Polygon - Face 层次结构,其中 verticesVertex 类型列表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/

相关文章:

java - 使用 retrofit2 和 RxAndroid 从 Spring WebFlux 获取响应

database-design - 没有 ORM 的领域丰富的应用程序

javascript - 我可以使数据结构显示为 HTML 元素吗?

javascript - 在 JavaScript 中隐藏对象的字段

thread-safety - Kotlin: "synchronized"使编译器不确定变量的初始化

java - 如何从发布构建中排除模块

java - OOP 设计以两种方式避免对象另一个对象

java - 如何正确使用Java比较器?

javascript - 如何在 Android(Java/Kotlin) App 中调用 Javascript 函数?

android - 未能解决 glide,现在 3rd-party Gradle 插件可能是原因