Kotlin 等于和哈希码生成器

Dav*_*vid 9 kotlin

我知道在 Kotlin 类中会自动创建一个 equals 和 hashcode,如下所示:

data class CSVColumn(private val index: Int, val value: String) {
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,有没有办法让实现只使用这些属性之一(例如index),而无需自己编写代码。原本非常简洁的类现在看起来像这样:

data class CSVColumn(private val index: Int, val value: String) {

    override fun equals(other: Any?): Boolean {
        if (this === other) {
            return true
        }
        if (javaClass != other?.javaClass) {
            return false
        }
        other as CSVColumn
        if (index != other.index) {
            return false
        }
        return true
    }

    override fun hashCode(): Int {
        return index
    }

}
Run Code Online (Sandbox Code Playgroud)

在带有 Lombok 的 Java 中,我可以执行以下操作:

@Value
@EqualsAndHasCode(of="index")
public class CsvColumn {
    private final int index;
    private final String value;
}
Run Code Online (Sandbox Code Playgroud)

如果有办法告诉 Kotlin 类似的东西会很酷。

tyn*_*ynn 7

数据类文档中您可以获得:

请注意,编译器仅将主构造函数中定义的属性用于自动生成的函数。要从生成的实现中排除属性,请在类体内声明它

所以,你必须执行equals(),并hashCode()手动或使用的帮助科特林编译器插件