I am curious why I can apply <= to both Int and Long, but == doesn't work. See playground:
fun main() {
val a = 0L
if (a == 0) {
// Compile error (Operator '==' cannot be applied to 'Long' and 'Int')
}
if (a <= 0) {
// No compile error
}
}
<= works simply because there is a compareTo overload defined in Long that takes Int:
class Long {
// ...
operator fun compareTo(other: Int): Int
// ...
}
<= is simply translated to a call to this (plus a comparison of the returned Int).
While == also translates to a call to equals(Any?) (with additional null checks), there is this bit in the spec that disallows comparing the quality of things of completely different type:
If type of
Aand type ofBare definitely distinct and not related by subtyping,A == Bis an invalid expression and should result in a compile-time error.
When comparing Int and Long values using == in Kotlin, the compiler will perform a type check and will determine that the types are not compatible. Therefore, it is not possible to compare Int and Long values using ==. There is no implicit widening conversions for numbers in Kotlin due to its documentation.
However, the <= operator is used for comparing numeric values, and it is overloaded for both Int and Long types. When comparing Int and Long values using <=, Long#compareTo() method is being called. As you can see in documentation, it can accept both Int and Long types as Parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With