Search code examples
kotlinequals

equal() function in Kotlin


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

Solution

  • 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