生成 equals()、hashCode() 等时忽略某些属性

Sah*_*Sah 2 kotlin

假设我有一个具有三个属性的数据类:

data class Product(
    val id: Int,
    val name: String,
    val manufacturer: String)
Run Code Online (Sandbox Code Playgroud)

如果我理解正确的话,Kotlin 将生成equals()hashCode()使用所有三个属性,如下所示:

override fun equals(other: Any?): Boolean {
    if (this === other) return true
    if (other == null || javaClass != other.javaClass) return false
    val that = other as Product?
    return id == that.id &&
            name == that!!.name &&
            manufacturer == that.manufacturer
}

override fun hashCode(): Int {
    return Objects.hash(id, name, manufacturer)
}
Run Code Online (Sandbox Code Playgroud)

那么如果我不想id被用在equals()and中怎么办hashCode()?有没有办法告诉 Kotlin 在生成这些函数时忽略某些属性?toString()和怎么样compareTo()

zsm*_*b13 5

对于数据类,这些函数是使用主构造函数中声明的所有属性生成的。来自官方文档

编译器自动从主构造函数中声明的所有属性派生以下成员:

  • equals()/hashCode() 对,
  • toString() 形式为“User(name=John,age=42)”,
  • componentN() 函数对应于按声明顺序排列的属性,
  • copy() 函数(见下文)。

如果您希望某个属性在实现时不被考虑在内,则必须将其移出主构造函数,或者自己实现这些函数。

有关类似问题的更多讨论请参见此处