Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does <= can be applied to Int and Long, but == can't?

Tags:

kotlin

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
    }
}
like image 422
J. Doe Avatar asked Oct 30 '25 00:10

J. Doe


2 Answers

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

like image 54
Sweeper Avatar answered Nov 01 '25 14:11

Sweeper


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.

like image 39
Mikhail Guliaev Avatar answered Nov 01 '25 13:11

Mikhail Guliaev