2016-10-29 39 views
5

我有一个类问题定义equals()方法操作

open class Texture 

,我想定义equals(other: Texture)操作

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

,但我得到

Error:(129, 5) Kotlin: 'operator' modifier is inapplicable on this function: must override ''equals()'' in Any

什么这是什么意思?

如果我改变,要

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

Accidental override, two declarations have the same jvm signature

回答

5

equals() operator function is defined in Any,所以它应该与兼容的签名被重写:它的参数otherAny?型的,它的返回值应该是Boolean或其子类型(它是最终的)

open class Texture { 
    // ... 

    override operator fun equals(other: Any?): Boolean { ... } 
} 

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

在IntelliJ IDEA的,你可以使用按Ctrl + Ø覆盖的成员,或按Ctrl + 插入产生equals() + hashCode()

+0

更新了答案,由于问题的更新。 – hotkey

+0

当'other'不是'Texture'的实例时,如何安排函数返回'false'? – saulspatz