19

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?

holi-java
  • 29,655
  • 7
  • 72
  • 83
Edy Bourne
  • 5,679
  • 13
  • 53
  • 101

2 Answers2

20

Indeed, you needn't an abstract class yet. you can just override the interface properties, for example:

interface B {
    val id: Int?
}

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

An interface has no constructors so you can't call the constructor by super(..) keyword , but you can using an abstract class instead. Howerver, a data class can't declare any parameters on its primary constructor, so it will overwritten the field of the superclass, for example:

//               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)
Community
  • 1
  • 1
holi-java
  • 29,655
  • 7
  • 72
  • 83
  • 1
    @EdyBourne Not at all. In fact, I'm confused by **superclass** word in the question and abuse **abstract class** at the first time. I realized it has some troubles to let a `data class` extends a `class` until I wrote down the answer. so I change my head and finally found that you just want to **implements** the interface *getters/setters* only. – holi-java Jul 17 '17 at 19:48
  • `open val` - is that right? Seems like `protected final` – Abhijit Sarkar Jul 17 '17 at 22:39
  • @Abhijit Sarkar Hi, there is no problem. Since it assert that its getter can be override and its back-field also is **final**. – holi-java Jul 17 '17 at 22:44
  • So it translates to a `private final` field with `protected` getter? – Abhijit Sarkar Jul 17 '17 at 22:56
  • 2
    @Abhijit Sarkar yeah, but the visibilitybis not changed getter is public. – holi-java Jul 17 '17 at 22:57
0
interface B {
    var id: Int?
}

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

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