How to properly extend (inherit) a data class in Kotlin? Possible workarounds
Hi everyone! I just started learning Kotlin and encountered an unexpected problem. I need to create a class hierarchy for modeling entities in an application. For example, there is a base class `User` with fields `id` and `email`, and I want to create a data class `AdminUser` from it that adds a `role` field.
I wrote this code:
```kotlin
data class User(val id: Long, val email: String)
data class AdminUser(val id: Long, val email: String, val role: String) : User(id, email)
```
But the compiler gives an error: "data class may not inherit from a data class". I googled it and realized that a data class in Kotlin cannot inherit from another data class because the compiler cannot generate correct `equals()`, `hashCode()`, `toString()`, and `copy()` methods for such a hierarchy.
But what should I do?
No answers yet.
Log in to leave an answer
Blogs
How to Write a REST API in C# in 30 Minutes: A Step-by-Step Guide
Security of C++ Applications: Top 10 Vulnerabilities and How to Avoid Them
JavaScript Libraries 2024: A Guide to the Ecosystem for Web Developers
OAuth 2.0 and JWT Authorization in Rust: A Step-by-Step Guide for Beginners