How to let a data class implements Interface / extends Superclass properties in Kotlin?

Viewed 13662

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?

2 Answers
interface B {
    var id: Int?
}

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

var a1:A = A(1)
var a2:A = A(null)
Related