What does the == operator mean in Kotlin?

Asked

Viewed 216 times

5

What does the === Kotlin operator mean, and how to use it? I found this snippet of code in the documentation, but I was left with doubts.

val boxedA: Int? = a
val anotherBoxedA: Int? = a
println(boxedA === anotherBoxedA) // !!!Prints 'false'!!!

1 answer

8


It is used to verify the referential equality, that is, if the references contained in the two variables are the same, therefore point to the same address and then the same object, which of course the equal value will also be equal.

In your example you have objects with the same value, but they are totally different objects. The Int? is a type by reference so each variable has a different object. If it were only the Int would be different.

It is used as opposed to == that only analyzes the value of the object, then it is possible that two different objects at different locations are equal if the analysis of their structure is equal. The way these values are checked depends on each object and can be customized in the type you create. There are cases where simple, or structural equality is actually equal to referential, but it’s only because the guy set it up like that. This has to do with the identity of the object.

To documentation say that.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.