Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin equals and hash code generator

Tags:

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) {
}

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
    }

}

In Java with Lombok, I can do something like:

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

Would be cool if there were a way to tell Kotlin something similar.

like image 999
David Avatar asked Feb 05 '23 00:02

David


1 Answers

From the Data Classes documentation you get:

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

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

like image 124
tynn Avatar answered Feb 06 '23 15:02

tynn