10

I need to inherit a data class A from data class B. I know that this is not feasible in Kotlin.

Question 1:
Why is this not feasible?

Question 2:
What may be a solution for this?

Example:

data class A(val data1 : String)
data class B(val data2 : String) : A()

How can I achieve this in Kotlin?

Pang
  • 9,564
  • 146
  • 81
  • 122
Stack
  • 1,164
  • 1
  • 13
  • 26
  • take a look at this post: https://stackoverflow.com/a/44266735/4035036 – Mosius Apr 16 '19 at 05:24
  • 1
    Possible duplicate of [Why Kotlin modifier 'open' is incompatible with 'data'?](https://stackoverflow.com/questions/44266602/why-kotlin-modifier-open-is-incompatible-with-data) – dey Apr 16 '19 at 05:28
  • 1
    https://stackoverflow.com/questions/26444145/extend-data-class-in-kotlin See the answer given by Andrey Breslav himself – Abhay Agarwal Apr 16 '19 at 10:59
  • 1
    Does this answer your question? [Extend data class in Kotlin](https://stackoverflow.com/questions/26444145/extend-data-class-in-kotlin) – Vadzim Jan 20 '22 at 21:07

2 Answers2

24

Question 1

Data class contains some generated methods, like hashCode, equals, copy,... You could break those methods in class extending data class, but kotlin needs to guarantee that they work properly. That's the reason for making data class impossible to extend.

Question 2

The only solution for that, when you need two data class is to create one more abstract class and derive these two data classes from it. You need to notice that data class in kotlin create hashcode, equals and toString, and other methods based on primary constructor, and that's why you need to override fields from Base class in data class constructor.

abstract class Base(open val data1: String)

data class A(override val data1: String): Base(data1)

data class B(override val data1: String,  val data2: String): Base(data1)
dey
  • 3,022
  • 1
  • 15
  • 25
1

you have to do like below.

abstract class A(open val data1 : String) {}

data class B(val data2 : String) : A(data1)
Mehul Kabaria
  • 6,404
  • 4
  • 25
  • 50