3

I have an abstract class:
abstract class SuperClass(private val privateVal: Int)

I have a data class extending the abstract class. (DataClass)

How can I take privateVal as an argument in the DataClass constructor and pass it to the SuperClass constructor?

The following won't work, because only vals and vars are allowed in a data class constructor:
data class DataClass(privateVal: Int) : SuperClass(privateVar)

user2851108
  • 31
  • 1
  • 3
  • Does this answer your question? [Extend data class in Kotlin](https://stackoverflow.com/questions/26444145/extend-data-class-in-kotlin) – Vadzim Dec 21 '21 at 13:41

1 Answers1

6

Data classes work differently than regular classes. As you have already noticed, data classes require properties in the constructors. Data classes and inheritance is hard, because you can't pass the values like in regular classes. And inheriting from a data class isn't possible either; they don't support open or abstract, which means it's final, and can't be inherited from.

Effectively, this isn't possible if you have a data class as the child:

class Something(something: Int, else: Int) : Parent (something, else)

However, Kotlin does support abstract vars and vals. If you absolutely need a data class as the child (though I do not recommend that; using a regular class might be better depending on your use case).

abstract class SuperClass {
    protected abstract val privateVal: Int
}
data class Overridden(override val privateVal: Int) : SuperClass()

Here it overrides the val in the constructor, meaning it would still work. The reason it's protected and not private is because it wouldn't be able to inherit if it's private.

Again though, I really recommend using regular classes instead of data classes here.

Zoe
  • 27,060
  • 21
  • 118
  • 148