Kotlin supports checking for equality in two ways; by comparing references, or by comparing the values stored in the references.
Kotlin's ==
operator is used to compare by value and is equivalent to calling the equals()
method as defined in Java. To perform referential equality, one must use the ===
operator instead, which would correspond to the normal ==
operator from Java.
In general, it is better to use the ==
operator to compare objects, because even if two objects have different addresses, it is possible that their structure and/or state could be exactly the same.
Only use ===
when you need to know if two references are pointing to the same object or not.
It is better to use the ==
operator to compare objects such as String
s, as it provides stronger conditions for equality.
val s1: String = "first string"
val s2: String = "second string"
if (s1 === s2) {
// ...
}
Use structural equality to compare strings.
val s1: String = "first string"
val s2: String = "second string"
if (s1 == s2) {
// ...
}