Bernhard
07/08/2025, 10:46 AMgildor
07/08/2025, 10:47 AMBernhard
07/08/2025, 10:51 AMHuib Donkers
07/08/2025, 11:33 AMdata class Person(val name: String, val age: Int)
data class Employee(val department: String, name: String, age: Int) : Person(name, age)
Now how would one use destructuring? Person::component2
has a different signature than `Employee::component2`:
fun doSomething(friend: Person) {
val (name, age) = friend
println("$name is $age year old")
}
doSomething(Employee("math", "Ben", 15))
Bernhard
07/08/2025, 11:34 AMBernhard
07/08/2025, 11:35 AMBernhard
07/08/2025, 11:35 AMHuib Donkers
07/08/2025, 11:36 AMBernhard
07/08/2025, 11:37 AMBernhard
07/08/2025, 11:38 AMgildor
07/08/2025, 11:39 AMBernhard
07/08/2025, 11:41 AMWout Werkman
07/08/2025, 11:55 AMequals
states that (x == y) == (y == x)
must always be true. One of many things that would break with data class inheritance.
I think that the feature you're looking for is structural typing. Meaning that if some type A
has all the functions of another type B
, then you can safely cast A
to B
. For example, that would make Sequence
and Iterable
to be exactly the same type.
TypeScript supports structural typing, and they consider `Employee > Person`:
type Person = { name: String, age: number }
type Employee = { department: String, name: String, age: number }
function foo(person: Person) {}
const employee: Employee = { department: "Gift Delivery", name: "Santa", age: 1713 }
foo(employee)
In your situation there's overlap in the behavior that both data classes have, which means there's 2 main options:
• Make an interface with the shared behavior (like you suggested)
• Make another data class that has the overlapping data. (Employee(department: Department, nameAndAge: NameAndAge)
)
I can imagine that both of them are suboptimal for your needs.Bernhard
07/08/2025, 11:59 AMBernhard
07/08/2025, 12:00 PMHuib Donkers
07/08/2025, 12:02 PMPerson
and Employee
from earlier, the problem @Wout Werkman describes with equals is (probably)
val a = Person("Ben", 15)
val b = Employee("math", "Ben", 15)
a.equals(b) // true
b.equals(a) // false
Bernhard
07/08/2025, 12:05 PMBernhard
07/08/2025, 12:06 PMBernhard
07/08/2025, 12:06 PMBernhard
07/08/2025, 12:08 PM