How to check object equality in Kotlin?

Unlike Java, Kotlin is purely object-oriented language. There are no primitives, everything is an object. With this said, you might be surprised by results.

Let’s compare two objects with equality operator:

object1 == object2

You expected to get false, right? But answer is true. Why? This code is translated to

a?.equals(b) ?: (b === null)

Basically safe equals check. Operator == in Kotlin checks for structural equality, not referential one. For not null values == will give you same results as equals method. And Android Studio even urges you to use this instead of equals. Same as in Java, you have to override this method for your own objects (or use data classes). How does equals method look in Kotlin class? Let’s use Android Studio to generate it (and hashcode) for our class containing 3 String variables.

class User(var username: String, var firstname: String, var lastName: String) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false
        other as User
        if (username != other.username) return false
        if (firstname != other.firstname) return false
        if (lastName != other.lastName) return false
        return true
    }
    override fun hashCode(): Int {
        var result = username.hashCode()
        result = 31 * result + firstname.hashCode()
        result = 31 * result + lastName.hashCode()
        return result
    }
}

Very similar to Java counterpart.

Kotlin extension functions (I will speak about them later) enable you to add new equals method implementation with different parameters. Kotlin already has one defined for String. If you want to check String equality ignoring case, in Java you call

s1.equalsIgnoreCase(s2)

In Kotlin there is

s1.equals(s2, true)

If you need to check structural integrity, use this operator ===.

Share this...
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *