Diffrence between == and === in kotlin

Understanding Equality in Kotlin

In Kotlin, understanding how equality works is crucial, and it primarily involves two types: Structural Equality (==) and Referential Equality (===).

Structural Equality (==)

Structural equality, denoted by the double equals sign (==), checks whether two objects are equal based on their content. This comparison is typically done using the equals() function. When you use the == operator, you're asking Kotlin to compare the values of the objects, not their references.

Referential Equality (===)

Referential equality, denoted by triple equals (===), checks whether two references point to the same object in memory. In other words, it verifies if two variables are referencing the exact same instance.

An Example Class

To illustrate these concepts, let's consider a sample class:

Note: This is NOT a data class. So, it will not implement the equals() method by default.

First, let's first compare Structural equality.



The output:


Let's take another example.

The output:

It also outputs false even though the name of both peson is the same because we have not implemented the equals() method.

Let’s take another example.

The output:

It outputs true as the references to both objects are the same now, no need of checking for the equals() method implementation.

Now, compare Referential equality.

The output:

It outputs false as the references to both objects are different.

Another example:

The output:

It outputs true as the references to both objects are the same now.

Till now, we have NOT implemented the equals() method, there are two ways to implement equals() method:

  1. Making the class a data class.

  2. Adding our own equals() method implementation.

Both will behave the same. So, let's go with the data class.

As our class Car was not a data class. Now, let's make our class a data class.

When we make it a data class, it implements equals() method internally.

Now, let's first compare Structural equality.

The output

Let’s take another example

The output:

It outputs true as the references to both objects are the same now, no need of checking for the equals() method implementation although it is a data class. The output will be the same even if it was not a data class as we have seen earlier.

Now, compare Referential equality. It has no impact due to the data class.

The output:

It outputs false as the references to both objects are different.

Another example:

The output:

It outputs true as the references to both objects are the same now.

Previous
Previous

Made by Google Event 2023 Highlights: A Look into the Future

Next
Next

Strengthening cybersecurity governance with the NIST Framework