Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 594
Edy Bourne Avatar asked Jul 17 '17 16:07

Edy Bourne


People also ask

Can a data class extend a data class Kotlin?

We cannot extend a data class but in order to implement the same feature, we can declare a super class and override the properties in a sub-class.

Can data class implement interface Kotlin?

Kotlin Data Class RequirementsData class can implement interfaces and extend to other classes. The parameters of the class can be either val or var type.

How do I extend an interface in Kotlin?

In Kotlin we use a single colon character ( : ) instead of the Java extends keyword to extend a class or implement an interface.

Can we extend class in Kotlin?

Kotlin provides the ability to extend a class or an interface with new functionality without having to inherit from the class or use design patterns such as Decorator. This is done via special declarations called extensions.


1 Answers

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)
like image 168
holi-java Avatar answered Oct 09 '22 05:10

holi-java