How to allow a data class to implement an interface / extends the properties of a superclass in Kotlin?

I have several data classes that include the var id: Int? field var id: Int? . I want to express this in an interface or superclass and have data classes extending it and setting this id when building them. However, if I try this:

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

He complains that I am redefining the id field, which I haha ​​..

Q How can I let the data class A in this case take the id when it is built and establish that the id declared in the interface or superclass?

+5
source share
1 answer

Indeed, you do not need an abstract class . you can just override 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 cannot invoke the constructor using the super(..) keyword, but you can use an abstract class . Howerver, the data class cannot declare any parameters on the primary constructor , so it will overwrite the field 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) 
+5
source

Source: https://habr.com/ru/post/1269908/


All Articles