Improved Equality Check

Types of equality checks

Just like Java, Kotlin also has two types of equality checks:

  • equals() method in Java, or == operator in Kotlin, is a comparison of values, called structural equality.
  • == operator in Java, or === in Kotlin, is a comparison of references, called referential equality. Referential equality compares references and returns true if the two references are identical—that is, they refer to the same exact instance. The operator === in Kotlin is a direct equivalent of the == operator in Java.

What is the difference?

But the structural equality operator == in Kotlin is more than the equals() method in Java. If you perform str1.equals(str2); in Java, you may run into a NullPointerException if the reference str1 is null. Not so when you use == in Kotlin. Kotlin’s structural equality operator safely handles null references. Let’s examine that with an example:

Get hands-on with 1200+ tech skills courses.