13

I have several data classes which include a var id: Int? field. I want to express this in an interface or superclass, and have data classes extending that and setting this id when they are constructed. However, if I try this:

interface B {
  var id: Int?
}

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

It complains I'm overriding the id field, which I am haha..

Q: How can I let the data class A in this case to take an id when it's constructed, and set that id declared in the interface or superclass?

4

1 回答 1

14

实际上,您还不需要抽象类。您可以只覆盖接口属性,例如:

interface B {
    val id: Int?
}

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

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

//               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)
于 2017-07-17T16:50:50.247 回答