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
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
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.