Hi, Today we will be comparing the equality operation between Java and Kotlin.
Let’s see this simple java code.

public static void main(String[] args)  {

    Student student1= new Student("Besho", 1)
    Student student2= new Student("Ali", 2)
    Student student3= new Student("Ali", 2)

    println(student1 == student2)
    println(student2 == student3)
    println(student1.equals(student2))
    println(student2.equals(student3))
}

The output will be

false
false
false
true

 

The == checks for referential equality, which means that it will return true if the instance on the left side is exact same instance as the one on the right.
On the other hand, the ‘.equals‘, will check for structural equality.
But in Kotlin that is not the case, he is the same code written in Kotlin
fun main(args: Array<String>)  {

    val student1 = Student("Besho", 1)
    val student2 = Student("Ali", 2)
    val student3 = Student("Ali", 2)

    println(student1 == student2 )
    println(student2 == student3 )
    println(student1.equals(student2) )
    println(student2.equals(student3) )
}

will give us the output

false 
true
false 
true
Why ?
In kotlin the == operator checks for structural equality, when it’s comparing instances, so the second and fourth checks are the same.

 

So how can we do a referential equality in kotlin ?
we use === operator !
[code]println(student2 === student3 )[/code]
same goes for not equal, it will look like this in kotlin
(structural !=, referential !== )
 
Another side note:
Kotlin handles Strings just like Java does, there’s only ever one instance of a specific string literal.
so let’s say we created 2 Strings with the same text like this
val student1="besho"
val student2="besho"
println(student1 === student2 )

we will get true as an output

Why?

The === as we said will check for referential equality, so If you use the string more than once in your code, you’re actually using the same string instance every time you refer to the string literal. This optimization comes from JVM which Kotlin also uses. So these two string literals are actually the exact same instance because when the jvm comes to execute this line of code, it looks in what’s called a string pool and it sees that it already has an instance of a string literal besho  so it just reuses it, because strings are immutable and so it’s safe for the jvm to do that.

That’s it for the equality in Kotlin, See you guys in the next post.