Issue
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?
Solution
==
does usually end up calling equals
, but it's not entirely equivalent. One of the inequivalences is a compile-time type check, designed to catch simple bugs. From the docs:
Kotlin checks the applicability of value equality operators at compile-time and may reject certain combinations of types for A and B. Specifically, it uses the following basic principle.
If type of A and type of B are definitely distinct and not related by subtyping, A == B is an invalid expression and should result in a compile-time error.
Informally: this principle means “no two objects unrelated by subtyping can ever be considered equal by ==”.
So because ""
and 1
are 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 for equals
.
Answered By - user2357112
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.