代码之家  ›  专栏  ›  技术社区  ›  Edy Bourne

如何让数据类在Kotlin中实现接口/扩展超类属性?

  •  15
  • Edy Bourne  · 技术社区  · 7 年前

    var id: Int? 领域我想用一个 界面 ,并让数据类对此进行扩展和设置 id 建造时。但是,如果我尝试这样做:

    interface B {
      var id: Int?
    }
    
    data class A(var id: Int) : B(id)
    

    身份证件 场,我是哈哈。。

    Q A 在这种情况下 当它被构建时,设置它 声明于 界面 超类

    1 回复  |  直到 7 年前
        1
  •  16
  •   Community Egal    4 年前

    事实上,你不需要 abstract class interface 属性,例如:

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

    界面 没有构造函数,因此无法通过调用构造函数 super(..) 关键字,但您可以使用 抽象类 相反Hower,a 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)