即使我实现了所有的 hashCode()、equals() 和 toString(),我是否应该使用 data class?

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

我有一个 class,它是一个字符串的解析结果,所以我必须将 toString() 强制执行到 return 那个源字符串而不是那些解析的值。它还具有自定义 equals()/hashCode() 机制。仍然将其标记为数据有什么好处吗class?

数据 classes 的自动生成部分是:

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.

componentN() 函数启用像 for ((a, b, c) in dataClass) { ... }

这样的解构

但是,数据class是无法继承。 (不过,您可以定义一个数据 class 来扩展另一个非数据 class。)

如果您认为某些 class 可能会扩展您的 class,那么请不要将其设为数据 class。

如果你认为以后没有class会扩展你的class,你可能需要销毁或copy()函数,那就把它做成数据class。