1

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.

enter image description here

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:

enter image description here

borjab
  • 11,149
  • 6
  • 71
  • 98
  • 1
    Have you actually checked what equals and hashCode functions it generates? I'm not seeing a difference (aside from the obvious Kotlin vs. Java syntax) – Jacob Jul 27 '21 at 18:53
  • Good point @Jacob. I have edited the question to include the information. It is exactly the same Java class after migrating to Kotlin my the automatic Intellij option – borjab Jul 28 '21 at 07:56
  • 1
    By default, the Kotlin compiler targets Java 1.6 bytecode. Have you tried changing your Kotlin compiler target to JVM 1.7 or later? – user31601 Jul 28 '21 at 11:22
  • Good point @user31601 but I have it set to 11 – borjab Jul 28 '21 at 15:35
  • 1
    Created a feature request: https://youtrack.jetbrains.com/issue/KTIJ-19340 – Margarita Bobova Aug 05 '21 at 06:37
  • Thanks you very much @MargaritaBobova – borjab Aug 05 '21 at 17:25

0 Answers0