The equals() function ==

The data class provides a useful function called equals(), which compares each property of the two classes. It comes back as true if all the properties of both classes are the same, otherwise it comes back as false. Let's take a look at an example:

  1. Declare a normal class, Person, and create two objects with similar values. Compare them with equal == operator:
class Person(var name : String, var age : Int, var height : Double)
fun main(args: Array<String>) {
val abid = Person("Abid", 40, 6.0)
val khan = Person("Abid", 40, 6.0)
if(abid == khan) {
println("Both Persons are same")
} else {
println("Different persons")
}
}
  1. Run this code and verify the output. The output is Different persons, although the values of both objects are the same. There are two objects created in the memory, abid and khan, and Kotlin verifies both objects by doing reference comparisons. The equal operator compares both objects and returns false as a result because both objects are pointing to different memory locations:

  1. Add the data keyword in the class declaration and execute this code again. This time, the output is Both persons are same because Kotlin performs a properties comparison in data classes.
The equals() function and the == operator are same. Behind the scenes, the == operator calls the equals function.

To understand this fully, carry out some more experiments by updating the property of an object and executing the following code:

if(abid.equals(khan)) {
println("Both Persons are same")
} else {
println("Different persons")
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.158.134