Kotlin等于和哈希码生成器 [英] Kotlin equals and hash code generator

查看:116
本文介绍了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.

推荐答案

来自

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

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().

So you have to implement equals() and hashCode() manually or with the help of a Kotlin Compiler Plugin.

这篇关于Kotlin等于和哈希码生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆