2016-10-29 40 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