Equality comparison in Kotlin

Comparison Symbol

1. Base

There are three equal operators in Kotlin==, ===, equals()

  1. ==in Kotlin is the same as calling the equals() function. The default comparison is the HashCode of the two objects. You can get the answer from the Any source code.
  2. The===operator is used to compare whether two object references are equal.
package kotlin

 * The root of the Kotlin class hierarchy. Every Kotlin class has [Any] as a superclass.
 * Kotlin Root node in class hierarchy, any class in kotlin is a subclass of Any.
public open class Any {
     * 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.
     * Note: In kotlin `=='will be translated if the parameters on both sides are not nullequals()Method,
    public open operator fun equals(other: Any?): Boolean

     * 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.
     * Multiple calls to hashCode from the same object should return the same value if both objects useequalsMethod gettrueSo these two objects
     * The hashCode of should be the same.
    public open fun hashCode(): Int

     * Returns a string representation of the object.
    public open fun toString(): String

2. String comparison

  1. If both strings have the same content then==, equals return true.
  2. If two medicines are equal then== return true.
// String comparison.
private fun test1() {
    val s1 = "Doug"
    // This is used to create two strings with different addresses.
    val s2 = String(charArrayOf('D', 'o', 'u', 'g'))
    // If two strings have the same value, hashCode will be equal.
    // === <=> equals, comparing the values of strings.
    println(s1 == s2)
    // ===Compares whether two objects have the same reference.
    println(s1 === s2)

3. General Classes

  1. If you do not override the equals method, all returns the same == as the == are comparison references.
  2. You can override equals and add your own logic
class Person(val name:String) {
     * equals General Writing.
    override fun equals(other: Any?): Boolean {
        return when (other) {
            !is Person -> false
            else -> this === other || this.name == other.name

Posted on Fri, 29 May 2020 12:54:13 -0400 by kjtocool