The new Certification Class of REST With Spring is out:

>> CHECK OUT THE COURSE

1. Overview

In this article, we are going to talk about the difference between “==” and “===” operators in Kotlin.

In Kotlin, just like in Java, we have two different concepts of equality, Referential equality, and Structural equality.

2. Referential Equality

For referential equality, we use the === symbol which allows us to evaluate the reference of an object (if it’s pointing to the same object). This is an equivalent of “==” operator in Java.

Let’s say we have two integers defined:

val a = Integer(10)
val b = Integer(10)

and we check them both by doing a === b, which will return false because they’re two separate objects, each pointing to a different location in memory.

3. Structural Equality

Now for structural equality, we use the == symbol that evaluates if both values are the same (or equal). This is usually achieved by implementing equals() method in Java.

So, using the same Integers example, we just need to do a == b, and in this case, it will return true, since both variables have the same value.

4. Comparing Complex Objects

If we want to check equality on more complex objects, the symbols will behave the same. Let’s say we have a User, which has a list of hobbies:

data class User(val name: String, val age: Int, val hobbies: List<String>)

The === will check reference equality and by conveniently using a List<> we can take advantage that the == operator, which will check the object and the data contained on the list.

5. Arrays Equality

For Arrays, as of Kotlin 1.1, we can check structural equality by using the infix functions contentEquals and contentDeepEquals:

val hobbies = arrayOf("Hiking, Chess")
val hobbies2 = arrayOf("Hiking, Chess")

assertTrue(hobbies contentEquals hobbies2)

6. Conclusion

This quick tutorial, showcased the difference between referential and structural equality in Kotlin, through a very simple example.

As always, the implementation of all of these examples and snippets can be found over on GitHub.

Note that this is a Maven-based project so it should be easy to import and run as is.

Go deeper into building a REST API with Spring:

>> CHECK OUT THE COURSE