gpt4 book ai didi

Kotlin等于和哈希码生成器

转载 作者:行者123 更新时间:2023-12-04 18:20:21 25 4
gpt4 key购买 nike

我知道,在Kotlin中,类将具有一个equals和自动创建的哈希码,如下所示:

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

我的问题是,有没有一种方法可以使实现仅使用这些属性之一(例如 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
}

}

在带有Lombok的Java中,我可以执行以下操作:
@Value
@EqualsAndHasCode(of="index")
public class CsvColumn {
private final int index;
private final String value;
}

如果有一种方法可以告诉Kotlin类似的东西,那就太酷了。

最佳答案

Data Classes文档中,您可以得到:

Note that the compiler only uses the properties defined inside the primary constructor for the automatically generated functions. To exclude a property from the generated implementations, declare it inside the class body



因此,您必须手动或在Kotlin编译器插件的帮助下实现 equals()hashCode()

关于Kotlin等于和哈希码生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50449603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com