我很好奇为什么我可以<=
同时适用于 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)
<=
之所以有效,是因为在takecompareTo
中定义了一个重载:Long
Int
class Long {
// ...
operator fun compareTo(other: Int): Int
// ...
}
Run Code Online (Sandbox Code Playgroud)
<=
简单地翻译为对此的调用(加上返回的比较Int
)。
虽然==
也转换为调用equals(Any?)
(带有额外的空检查),但规范中有一点不允许比较完全不同类型的事物的质量:
如果 type of
A
和 type ofB
明确不同且与子类型无关,A == B
则为无效表达式,并应导致编译时错误。
归档时间: |
|
查看次数: |
96 次 |
最近记录: |