Sobes.tech
Junior — Middle

Is it possible to override methods in a data class in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, a data class automatically generates equals(), hashCode(), toString(), as well as copy() and destructuring components. Overriding these methods in a data class is possible and sometimes necessary if you need to change the default behavior.

Example of overriding toString() in a data class:

data class User(val name: String, val age: Int) {
    override fun toString(): String {
        return "User(name=$name)" // for example, hiding the age
    }
}

Thus, a data class does not prohibit overriding methods, but it is important to remember that some methods are crucial for correct data handling, and their overriding should be justified.