Kotlin等于和哈希码生成器

标签 kotlin

我知道,在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/

相关文章:

android - 如何为 Kotlin 和 Android 设置 Mockito

java - 以编程方式关闭屏幕

android - Kotlin Map 项目列表流

kotlin - 如何防止 JUnit5 打印堆栈跟踪?

firebase - Kotlin - 可序列化类中的初始化 block 只能读取默认属性值

kotlin - 将接收参数作为参数的函数传递给类扩展方法

android - Unresolved reference : font in Android Studio

kotlin - RxJava 2 在单元测试中覆盖 IO 调度程序

kotlin - 如何访问 Kotlin 子类上的 Java 静态方法?

android - 外部播放器 : Custom AudioProcessor - Equalizer