kotlin - Kotlin 中相等运算符 (==) 导致编译错误的条件是什么?
问题描述
Kotlin 中相等运算符 (==) 导致编译错误的条件是什么?
当然,比较相同的类型是可以的。
fun compare1(x: Int) = x == 1
比较不同的类型会导致错误:
fun compare2(x: String) = x == 1
运算符 '==' 不能应用于 'String' 和 'Int'
但是与泛型类型相比是可以的,尽管 T 可能是字符串:
fun <T> compare3(x: T) = x == 1
解决方案
==
不能应用于不兼容的类型,即一个对象不能同时具有两种类型。请注意,即使它实际上会返回,这也适用true
:
class X(val n: Int) {
override fun equals(other: Any?) = x is Int
}
public fun main(){
println(X(0) == 0) // Operator '==' cannot be applied to 'X' and 'Int'
}
假设equals
“不应该”返回true
不兼容的类型。
所以compare3
重要的不是T
可能是String
,而是可能是Int
,所以这种比较有时是有道理的。
推荐阅读
- ios - UIPageControl 的 IBOutlet 或事件不在 StoryBoard 中
- c# - 为什么 ResourceWriter 不生成有效的 .resx 文件?
- python - 具有 i 和 %r 替换的基本 Python 循环
- ruby-on-rails - rake 任务 db:full_reset 有什么作用?
- vba - VBA Excel将行从一张表复制到另一张表中具有特定值的行
- android - 使用 Sceneform 生态系统有问题地旋转 3D 模型
- c# - 有没有办法返回作为子类的类型?
- oracle - NetSuite:日期之间的差异不包括交易公式的周末
- javascript - 如何使用量角器单击我的单选按钮?
- clojurescript - 使用 goog.dom.animationFrame 递归调用