Kotlin: Intrinsics.areEqual infinite loop (stack overflow)

Viewed 1102
java.lang.StackOverflowError
    at kotlin.jvm.internal.Intrinsics.areEqual(Intrinsics.java:164)
    at plugin.interaction.inter.teleports.Category.equals(Category.kt)
    at kotlin.jvm.internal.Intrinsics.areEqual(Intrinsics.java:164)
    at plugin.interaction.inter.teleports.Destination.equals(Destination.kt)

Happens from a .equals comparison between two non-relationship data classes.

Major bug.

data class Category(val name: String, val destinations: MutableList<Destination>)

data class Destination(val category: Category, val name: String)
2 Answers

Well in my case I was overriding equals method like:

override fun equals(other: Any?): Boolean {
        // some code here
        if (other==this)
            return true
       // some code here
    }

equals and == in java

In java when we use equals(for ex: str1.equals(str2)) it checks the content of two object(for custom objects you must have to override equals and check all the values of objects otherwise Object class's equals method just compare reference, which is same as ==), but if we use ==(for ex: str1==str2) operator, it checks the reference of both objects.


== in kotlin

But in case of kotlin when we use == operator, it checks the content(data or variable) of objects only if they are object of data class. And == operator checks reference for normal class.

when we use == it will call the equals method.


So in my overridden equals method when other==this will execute it will call eaquals method again, and that will call eaquals method again and make an infinite loop.

So to make it work we need to change == to ===(this will check the reference of both operator), like:

 if (other===this)
     return true

Note: .equals and == are same until we use them with Float or Double. .equals disagrees with the IEEE 754 Standard for Floating-Point Arithmetic, it returns a false when -0.0 was compared with 0.0 whereas == and === returns true

You can check reference here

Related