Override Property/Getter for Kotlin Data Class

July 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 possible
data 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

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:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.