Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: How to inherit property in data class

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?

like image 739
Yarick Avatar asked Oct 10 '17 15:10

Yarick


People also ask

Can data classes inheritance?

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.

How do you get inheritance in Kotlin?

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.

How do you extend data class to another 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.

How do you access the object property in Kotlin?

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.


1 Answers

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.

like image 67
hotkey Avatar answered Oct 07 '22 07:10

hotkey