首页 > 解决方案 > Kotlin 中相等运算符 (==) 导致编译错误的条件是什么?

问题描述

Kotlin 中相等运算符 (==) 导致编译错误的条件是什么?

当然,比较相同的类型是可以的。

fun compare1(x: Int) = x == 1

比较不同的类型会导致错误:

fun compare2(x: String) = x == 1

运算符 '==' 不能应用于 'String' 和 'Int'

但是与泛型类型相比是可以的,尽管 T 可能是字符串:

fun <T> compare3(x: T) = x == 1

标签: kotlin

解决方案


==不能应用于不兼容的类型,即一个对象不能同时具有两种类型。请注意,即使它实际上会返回,这也适用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,所以这种比较有时是有道理的。


推荐阅读