假设我有一个具有三个属性的数据类:
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()?
| 归档时间: |
|
| 查看次数: |
3962 次 |
| 最近记录: |