8

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?

1 Answer 1

21

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.