为什么<=可以应用于Int和Long,而==却不能?

J. *_*Doe 4 kotlin

我很好奇为什么我可以<=同时适用于 Int 和 Long,但==不起作用。参见游乐场

fun main() { 
    val a = 0L
    
    if (a == 0) { 
        // Compile error (Operator '==' cannot be applied to 'Long' and 'Int')
    }
    
    if (a <= 0) { 
        // No compile error
    }
}
Run Code Online (Sandbox Code Playgroud)

Swe*_*per 5

<=之所以有效,是因为在takecompareTo中定义了一个重载:LongInt

class Long {
    // ...
    operator fun compareTo(other: Int): Int
    // ...
}
Run Code Online (Sandbox Code Playgroud)

<=简单地翻译为对此的调用(加上返回的比较Int)。

虽然==也转换为调用equals(Any?)(带有额外的空检查),但规范中有一点不允许比较完全不同类型的事物的质量:

如果 type ofA和 type ofB明确不同且与子类型无关,A == B则为无效表达式,并应导致编译时错误。