I'm currently learning Kotlin and encountered a behavior that I find puzzling. Here are the two lines of code that have me confused:
"".equals(1) // not compile error
"" == 1 // compile error
"".equals(1) - This line compiles and runs without any issues.
"" == 1 - However, this line results in a compile-time error.
From my understanding, in Kotlin, the == operator is translated into a call to the equals method. So I'm curious why the first statement is considered valid while the second one is not, despite both seemingly attempting to do the same comparison between a String and an Int.
Could someone explain the underlying mechanics in Kotlin that make the first statement compile and run, but not the second?
==does usually end up callingequals, but it's not entirely equivalent. One of the inequivalences is a compile-time type check, designed to catch simple bugs. From the docs:So because
""and1are unrelated by subtyping, Kotlin decides that you probably made a mistake when writing this expression, and it aborts with a compile-time error. This check doesn't apply forequals.