I have the following class that acts as a base for a few other classes:
abstract class BaseFitness: Comparable<BaseFitness> { var valid: Boolean = false fun invalidate() { valid = false } abstract fun value(): Double abstract fun copy(): BaseFitness override operator fun equals(other: Any?): Boolean = if (other is BaseFitness) this.value() == other.value() else throw IllegalArgumentException("Can only compare to another class derived from BaseFitness.") override fun compareTo(other: BaseFitness): Int = this.value().minus(other.value()) .let { if (it.isNaN()) 0.0 else it } .sign.toInt() @JvmName("compareToOperator") operator fun compareTo(other: Any?): Int = if (other is BaseFitness) this.compareTo(other) else throw IllegalArgumentException("Can only compare to another class derived from BaseFitness.") } Now in this class I want to implement basic comparison behaviour.
Basically I want to be able to do:
if (fit1 == fit2) { /* do stuff */ }if (fit1 > fit2) { /* do stuff */ }if (fit1 < fit2) { /* do stuff */ }myFitnessSequence.max()
The equals() and compareTo() operator funcs take care of the first 3 items. However for the last item I need BaseFitness to implement Comparable. Problem is that when I implement comparable and add the non-operator compareTo() method somehow equals() breaks with this message:
'operator' modifier is inapplicable on this function: must override ''equals()'' in Any I tried doing the same thing I did with compareTo(), just having 2 implementations of equals(), one marked as an operator and one left as a method and adding @JvmName to one of them and I get
'@JvmName' annotation is not applicable to this declaration Right now my options are basically to either choose to keep and == operator but not implement Comparable or give up == to use comparable.
equalsimplementation breaks the contract. It should be safe to compare it to anything (and simply return false for other types of objects).