Search code examples
kotlindata-class

Should I use data class even if I implement all of hashCode(), equals() and toString()?


I have a class which is the parse result of a string, so I have to enforce the toString() to return that source string instead of those parsed values. It also has custom equals()/hashCode() mechanism. Is there any benefit to still mark it as a data class?


Solution

  • The auto-generated parts of data classes are:

    The compiler automatically derives the following members from all properties declared in the primary constructor:

    - equals()/hashCode() pair,
    - toString() of the form "User(name=John, age=42)",
    - componentN() functions corresponding to the properties in their order of declaration,
    - copy() function.
    

    If any of these functions is explicitly defined in the class body or inherited from the base types, it will not be generated.

    The componentN() function enables destructuring like for ((a, b, c) in dataClass) { ... }

    However, data classes CANNOT be inherited. (You can define a data class that extends another non-data class though.)

    If you think that it is possible that some classes extend your class, then do not make it a data class.

    If you think that no class will extend your class in the future, and you maybe need the destruction or copy() function, then make it a data class.