Kotlin provides an additional feature of comparing the instances of a particular type in two different ways. This feature makes Kotlin different than the other programming languages.
The two types of equality are –
- Structural Equality
- Referential Equality
Structural Equality –
Structural equality is checked through the == operator and its inverse != operator. By default, the expression containing x==y is translated into the call of equals() function for that type.
x?.equals(y) ?: (y === null)
states that if x is not equal to null, it calls the function equals(y), otherwise if x is found to be null it will checks for y is referentially equal to null.
Note – When (x == null) then automatically it will be converted to referential equality (x === null) so no need of code optimization here.
Thus, to use == on instances of a type the type must override the equals() function. For a string, the structural equality compares the contents.
Referential Equality –
The referential equality in Kotlin is checked through the === operator and its inverse !== operator. This equality returns true only if both the instances of a type point to the same location in memory. When used on types that are converted into primitives type at runtime, the === check is converted into == check and !== check is converted into != check.
Kotlin program to demonstrate the structural and referential eqaulity –
Two squares are structurally equal Two squares are not referentially equal
- Kotlin Data Types
- Hello World program in Kotlin
- Kotlin | Retrieve Collection Parts
- Destructuring Declarations in Kotlin
- Kotlin labeled continue
- Introduction to Kotlin
- Kotlin Type Conversion
- Kotlin Exception Handling | try, catch, throw and finally
- Kotlin if-else expression
- Kotlin Environment setup for Command Line
- Kotlin constructor
- Kotlin Environment setup with Intellij IDEA
- Kotlin Nested class and Inner class
- Kotlin Variables
- Kotlin Operators
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.