【问题标题】:How to let a data class implements Interface / extends Superclass properties in Kotlin?如何让数据类在 Kotlin 中实现接口/扩展超类属性?
【发布时间】:2017-07-17 16:44:40
【问题描述】:

我有几个数据类,其中包括一个var id: Int? 字段。我想在 interfacesuperclass 中表达这一点,并让数据类扩展它并在构造它们时设置它 id。但是,如果我尝试这样做:

interface B {
  var id: Int?
}

data class A(var id: Int) : B(id)

它抱怨我覆盖了id 字段,我是哈哈..

Q:在这种情况下,如何让数据类A 在构造时采用id,并在接口 中声明id em> 还是超类

【问题讨论】:

    标签: inheritance properties kotlin data-class


    【解决方案1】:

    确实,您还不需要abstract class。您可以直接覆盖 interface 属性,例如:

    interface B {
        val id: Int?
    }
    
    //           v--- override the interface property by `override` keyword
    data class A(override var id: Int) : B
    

    interface 没有构造函数,因此您不能通过 super(..) 关键字调用构造函数,但您可以使用 abstract class 代替。但是,data class 不能在其primary constructor 上声明任何参数,因此它将覆盖超类的字段,例如:

    //               v--- makes it can be override with `open` keyword
    abstract class B(open val id: Int?)
    
    //           v--- override the super property by `override` keyword
    data class A(override var id: Int) : B(id) 
    //                                   ^
    // the field `id` in the class B is never used by A
    
    // pass the parameter `id` to the super constructor
    //                            v
    class NormalClass(id: Int): B(id)
    

    【讨论】:

    • 谢谢,这正是我需要知道的。
    • @EdyBourne 一点也不。事实上,我第一次被问题中的 superclass 词弄糊涂了,滥用了 abstract class。我意识到让data class 扩展class 有一些麻烦,直到我写下答案。于是我换了个思路,最后发现你只想实现接口getters/setters而已。
    • open val - 对吗?好像protected final
    • @Abhijit Sarkar 嗨,没问题。因为它断言它的 getter 可以被覆盖并且它的后字段也是 final.
    • @Abhijit Sarkar 是的,但是可见性bis not changed getter 是公开的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    相关资源
    最近更新 更多