New operators

I have a suggestion for two new operators which, it seems to me, are lacking from a consistency perspective. The introduction of these would solve several old problems.

Kotlin got it right as far as making a clear distinction between == (structural equality) and === (referential equality). But there is one other important equality, namely comparative equality. By that I mean what the comparison operators refer to (<, <=, >=, >). There is one operator clearly missing in this series, namely “=”.

One could also put this as that there are operators expressing compareTo()<0, compareTo()>0 but not compareTo()=0.

Now, as “=” is regrettably already taken, something else would have to do, For the negation, I thing “<>” is an obvious choice, but for the positive version, perhaps “=?”, or possibly “><”.

These should be implemented in exactly the same way as the other comparison operators, i e by referring to compareTo().

This would solve:

a) testing equality between different types:

val a = 1
val b = 1L

a < b gives false
a > b gives false
a <= b gives true
a >= b gives true
a == b is not testable

With the new operators,
a =? b gives true, while
a <> b gives false.

b) custom numeric types
It is not possible to extend equals() on existing classes such as Int. But one can easily add compareTo(custom type):

class MyNumber(val v:Int) {
	operator fun compareTo(other: Int): Int {
		return v.compareTo(other)
	}	
	operator fun compareTo(other: myNumber): Int {
		return v.compareTo(other.v)
	}
}
operator fun Int.compareTo(other: Mynumber) = compareTo(other.v)

With the new operators, you can write:

val a = MyNumber(5)

if (a =? 5) …

See also Overloading == with different types of operands

c) the BigDecimal problem:

Comparing BigDecimals for numeric equality requires using compareTo(), not equals(), since equals also tests scale. With the new operators, you can use them consistently in all contexts where numeric equality is relevant.

see BigDecimal (Java Platform SE 8 )
also: BigDecimal comparison?

I believe this is a very much better way of solving these problems than the Groovy way (using compareTo for == instead of equals for objects implementing Comparable) or the Scala way (allowing user defined new operators). Letting == correspond to equals and separate operators to compareTo seems to me in line with Kotlin’s ambitions to be clear and simple.

1 Like