【问题标题】:Problems defining equals() operator定义 equals() 运算符的问题
【发布时间】:2016-10-29 17:09:52
【问题描述】:

我有课

open class Texture

我想定义equals(other: Texture) 运算符

operator fun equals(other: Texture) = ...

但我明白了

Error:(129, 5) Kotlin: 'operator' 修饰符不适用于此函数:必须覆盖 Any 中的 ''equals()''

什么意思?

如果我把它改成

operator fun equals(other: Any) = ...

意外覆盖,两个声明具有相同的 jvm 签名

【问题讨论】:

    标签: operator-overloading kotlin


    【解决方案1】:

    equals() operator function is defined in Any,所以它应该被一个兼容的签名覆盖:它的参数other应该是Any?类型,它的返回值应该是Boolean或者它的子类型 (这是最终的)

    open class Texture {
        // ...
    
        override operator fun equals(other: Any?): Boolean { ... }
    }
    

    没有the override modifier,您的函数将与Any::equals 冲突,因此会意外覆盖。此外,equals() 不能是扩展名 (just like toString()),也不能在接口中被覆盖。

    在 IntelliJ IDEA 中,您可以使用 Ctrl+O 覆盖成员,或 Ctrl+Insert生成equals()+hashCode()

    【讨论】:

    • 由于问题的更新,更新了答案。
    • other不是Texture的实例时,你如何安排函数返回false
    • @saulspatz:我猜第一行可能是if (other == null || other !is Texture) return false
    猜你喜欢
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多