CS.kotlin.CharSequence.其精髓在于:

class CS  (val sequence: CharSequence = "") : CharSequence {
... override get/length in interface CharSequence 
    override fun equals(other: Any?): Boolean =
            (this === other) || ((other is String) && this.sequence.equals(other))
}

The compiler objects to CS("hello") == "hello" as: Operator '==' cannot be applied to 'CS' and 'String'. It has no problems with CS("hello") == "hello" as Any or CS("hello").equals("hello") which both work.

我做错了什么?

推荐答案

I'm not certain of the reason for this error, but it might be related to a deeper problem with your approach…

In Kotlin (and Java), the equals() method has a fairly tight specification.  One condition is that it must be symmetric: whenever a and b are not null, a.equals(b) must always give the same result as b.equals(a).

但是你的实现没有通过这个测试,因为CS("abc").equals("abc")返回true,而"abc".equals(CS("ABC"))false,这是因为你的类知道CharSequence,比如String,但是String不知道你的类.

这是不容易的.一般来说,允许一个类的实例只等于该类的实例要安全得多.如果你控制这两个类,那么有办法解决,但它们非常微妙和复杂.(也许最好的解释是Martin Odersky et al.)

So most implementations of equals() tend to work along these lines:

override fun equals(other: Any?)
    = (other is ThisClass)
    && field1 == other.field1
    && field2 == other.field2
    // ...

正如我所说的,我不知道为什么Kotlin编译器在您的情况下抱怨.可能是它发现了这个问题的某些方面,也可能是一些无关的问题.但是我不认为您能够以等价性判断会做您想做的事情的方式修复您的程序,所以也许最好将此作为一个提示,try 一种稍微不同的方法!

Kotlin相关问答推荐

创建具有共同父类型的两种不同类型对象的列表的最有效方法是什么?

我可以检测一个函数是否在Kotlin中被递归调用(即,重入)吗?

Android Jetpack编写androidx.compose.oundation.lazy.grid.Items

jOOQ Kotlin Coroutines - Select all and exists查询

如何优雅地声明一个StateFlow?

如何在 kotlin 中的数据类中为变量提供多种类型

为什么 Kotlin 在将协变类型参数转换为不变类型参数时会产生 Unchecked Cast 警告?

Kotlin 可空泛型

如何将字符串格式化为电话号码kotlin算法

parallelStream()和asSequence().asStream().parallel()之间的区别

jetpack compose 将参数传递给 viewModel

Kotlin 静态函数:伴生对象,@JvmStatic @JvmField

如何用 kotlin 打包 List

Kotlin 单元测试 - 如何模拟 Companion 对象的组件?

使用 clear() 删除 EncryptedSharedPreferences 不起作用

API 26 上未显示 Android 通知

将 androidx.constraintlayout:constraintlayout lib 更新到 2.0.2 版本后出现崩溃 isRtl () null 引用

Kotlin:测试中的 java.lang.NoSuchMethodError

Kotlin中的嵌套let块

java.lang.NoClassDefFoundError:解析失败:Lkotlin/time/MonoClock