Search code examples
inheritancekotlindata-class

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?


Solution

  • 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.