I want to generate Kotlin equal and hashcodes using the Java 7 methods just as we usually do for Java. Let's assume that converting the class to a data class is not an option.
In IntelliJ, for Java, I can choose my Equal and HashCode template to implement it with the much more elegant and compact Java 7 version.
However in Kotlin I am redirected directly to a menu to choose the properties.
This is a Java generated one:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Delete delete = (Delete) o;
return var == delete.var && Objects.equals(foo, delete.foo);
}
@Override
public int hashCode() {
return Objects.hash(foo, var);
}
This is a Kotlin one:
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Delete
if (foo != other.foo) return false
if (`var` != other.`var`) return false
return true
}
override fun hashCode(): Int {
var result = foo.hashCode()
result = 31 * result + `var`
return result
}
You may appreciate that the Kotlin version is coding the number hash with prime numbers itself. That is because it is not using Objects.hash or Objects.equals
Note: I am usinng Intellij 2021.1.3 Ultimate
Update:
I have my kotlin target version set to Java 11 with:
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<configuration>
<compilerPlugins>
<plugin>spring</plugin>
</compilerPlugins>
<jvmTarget>${java.version}</jvmTarget>
I had also updated the main config here: