Kotlin等于和哈希码生成器 [英] Kotlin equals and hash code generator
本文介绍了Kotlin等于和哈希码生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道在Kotlin中,类将具有一个等于值和自动创建的哈希码,如下所示:
I am aware that in Kotlin classes will have an equals and hashcode created automatically as follows:
data class CSVColumn(private val index: Int, val value: String) {
}
我的问题是,有没有一种方法可以让实现仅使用这些属性之一(例如index
)而无需自己编写代码.原来是非常简洁的类,现在看起来像这样:
My question is, is there a way to have the implementation just use one of these properties (such as index
) without writing the code yourself. What was otherwise a very succinct class now looks like this:
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
}
}
在带有Lombok的Java中,我可以做类似的事情:
In Java with Lombok, I can do something like:
@Value
@EqualsAndHasCode(of="index")
public class CsvColumn {
private final int index;
private final String value;
}
如果有一种方法可以告诉Kotlin类似的东西,那会很酷.
Would be cool if there were a way to tell Kotlin something similar.
推荐答案
查看全文