Override Property/Getter for Kotlin Data Class

Jul 24, 2018

You can't override getter in kotlin data class with error of Data class primary constructor must have only property (val/ var) parameters.

// not possibledata class Test(id: String) {    val id: String        get() = if (!id.isEmpty()) id else "Is Empty"}

While you can do so in a regular class.

class Test(id: String) {    val id: String        get() = if (!id.isEmpty()) id else "Is Empty"}

My advice is it can't be done / don't do it. Instead, use a normal class

  • Are you sure you need equals / hashCode or copy methods of data class?
  • You can generate equals / hashCodeandroid-studio-generate-equals-and-hashcode-methods-for-kotlin methods for normal class.

There is hack if you really insist, though I don't really like the implementation.

data class Test(private val _id: String) {    val id: String        get() = if (!_id.isEmpty()) _id else "Is Empty"}

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.