I have abstract Token class declared like this:
abstract class Token(var index: Int = 0) {
open fun merge(toMerge: Token): Token? {
return null
}
}
I want to inherit index property in data class, like this:
data class CloseLoop(index: Int, var openLoopIndex: Int = 0) : Token(index)
But it gives me error Data class primary constructor must have only property (val / var) parameters
What i have to do to fix this?
You can inherit a data class from a non-data class. Inheriting a data class from another data class is not allowed because there is no way to make compiler-generated data class methods work consistently and intuitively in case of inheritance. Yes, that's correct.
Everything in Kotlin is by default final, hence, we need to use the keyword open in front of the class declaration to make it inheritable for other classes. Kotlin uses operator ":" to inherit a class.
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.
Use the dot operator to access an object's properties and functions. A constructor runs when you initialize an object. You can define a property in the primary constructor by prefixing a parameter with val or var . You can define a property outside the constructor by adding it to the class body.
There are at least two workarounds:
Make the property open
and override it in the data class primary constructor declaration:
abstract class Token(open var index: Int = 0)
data class CloseLoop(
override var index: Int,
var openLoopIndex: Int = 0
) : Token(index)
Declare a property with another name and initialize the base class with it:
data class CloseLoop(val theIndex: Int, var openLoopIndex: Int = 0) : Token(theIndex)
Make it private
if you find it appropriate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With