• Latest Code...

    Override Equal, HashCode and ToString in Kotlin

    We all know that override equal(), hashcode() and toString() in java, Here in Kotlin by default implementation, you don't have to need override them. However, if you want to override toString, equals and hashCode, you have to do this.

    equals: 
    open operator fun equals(other: Any?)Boolean
    Indicates whether some other object is "equal to" this one. Implementations must fulfil the following requirements:
    • Reflexive: for any non-null reference value x, x.equals(x) should return true.
    • Symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
    • Transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true
    • Consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
    Note that the == operator in Kotlin code is translated into a call to equals when objects on both sides of the operator are not null.
    hashCode:
    open fun hashCode()Int
    Returns a hash code value for the object. The general contract of hashCode is:
    • - Whenever it is invoked on the same object more than once, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.
    • - If two objects are equal according to the equals() method, then calling the hashCode method on each of the two objects must produce the same integer result.
    toString:
    open fun toString()String
    Returns a string representation of the object.

    ------------------------------------------------------------
    Here is the full implementation kotlin code:

    Output looks like
    without override equals , hashCode and toString method
    false
    false
    euquals
    false
    false
    toString
    co.prandroid.firstkotlin.MainActivity$User@4c83bb6
    hashCode
    80231350
    with override equals , hashCode and toString method
    false
    true
    euquals
    false
    true
    toString
    Client(name=john, code=12345)
    hashCode
    101315726
    #HappyCoding #ILoveKotlin

    Circle

    Most recent Elastic Search tutorials for beginner, intermediate and advance level developer, Yubraj Pokharel, in CodingWorkspace