Home > Back-end >  equal() function in Kotlin
equal() function in Kotlin

Time:03-08

I need if two objects are equal() need to print("Equal") if objects are not equal -> "Not equal".I can not find mistake of this codeThis is my code in IntelliJ IDEA As a side note, when we override equals(), it is recommended to also override the hashCode() method. If we don’t do so, equal objects may get different hash-values; and hash based collections, including HashMap, HashSet, and Hashtable do not work properly (see this for more details). We will be covering more about hashCode() in a separate post. References:

internal class Complex(private val re: Double, private val im: Double) {
    // Overriding equals() to compare two Complex objects
    fun equals(o: Object): Boolean {

        // If the object is compared with itself then return true
        if (o === this) {
            return true
        }

        /* Check if o is an instance of Complex or not
          "null instanceof [type]" also returns false */if (o !is Complex) {
            return false
        }

        // typecast o to Complex so that we can compare data members
        val c = o as Complex

        // Compare the data members and return accordingly
        return (java.lang.Double.compare(re, c.re) == 0
                && java.lang.Double.compare(im, c.im) == 0)
    }
} // Driver class to test the Complex class

    fun main(args: Array<String>) {
        val c1 = Complex(12.0, 15.0)
        val c2 = Complex(10.0, 15.0)
        if (c1 == c2) {
            println("Equal ")
        } else {
            println("Not Equal ")
        }
    }

CodePudding user response:

In Kotlin, you use Any instead of Object. It will not allow you to test if your class instance is an Object, only Any.

Also, you are failing to override equals since you didn't use the override keyword. The argument needs to be Any?, not Object.

Change

fun equals(o: Object): Boolean {

to

override fun equals(o: Any?): Boolean {

Also, in this case, you should use a data class so you won't have to write your own equals() implementation in the first place.

And in the future, when you aren't using a data class, you can use the IDE option to generate equals and hashcode for you automatically.

CodePudding user response:

A data class would make more sense:

data class Complex(
  private val re: Double,
  private val im: Double
)

val c1 = Complex(12.0, 15.0)
val c2 = Complex(10.0, 15.0)

if (c1 == c2) {
  println("Equal")
} else {
  println("Not Equal")
}

Output: Not Equal

  • Related