Sobes.tech
Junior — Middle

What functions or methods can be overridden in a Kotlin Data Class?

sobes.tech AI

Answer from AI

In Kotlin, a data class automatically generates several functions that can be overridden if necessary:

  • equals(other: Any?): compares objects by value.
  • hashCode(): computes a hash code based on properties.
  • toString(): string representation of the object.
  • copy(): creates a copy of the object with the option to modify some properties.
  • componentN(): functions for destructuring (e.g., component1(), component2(), etc.).

If you need to change the behavior of the class, you can override these methods manually. For example, overriding toString() for custom output:

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

However, keep in mind that overriding these functions cancels the automatic generation, and you need to ensure correct implementation manually.