For objects, there are two types of equality.
Type | Meaning |
---|---|
referential equality | two separate references to the exact same instance in memory. |
structural equality | two objects are separate instances in memory but have the same value. |
To test whether two references point to the same instance, we use the === operator or !== for negation:
val a = File("/a.doc") val b = File("/a.doc") val sameRef = a === b //false
To test whether two objects have the same value, we use the == operator or != for negation.
These function calls are translated into the use of the equals function that all classes must define.
val a = File("/a.doc") val b = File("/a.doc") val structural = a == b //true
It is up to the creator of a class to determine what structural equality means for that class.
The == operator is null safe. We don't need to worry if we are testing a null instance as the compiler will add the null check.