Why does this code compile?
This compiles because the overridden interface method, Comparable<T>.compareTo
, is itself an operator fun
.
/**
* Compares this object with the specified object for order. Returns zero if this object is equal
* to the specified [other] object, a negative number if it's less than [other], or a positive number
* if it's greater than [other].
*/
public operator fun compareTo(other: T): Int
As the function overrides this, it is also an operator function.
When exactly is
operator
required?
operator
in general is required whenever you wish to be able to use a function as if it were an operator, since operator usages are simply compiled to function calls (except on primitive types, etc.)
That is, foo += bar
, for example, is equivalent to foo.plusAssign(bar)
, foo[bar] = baz
is equivalent to foo.set(bar, baz)
, etc.
Personally I prefer specifying operator
wherever possible even if it is not required, for readability reasons.
If MyDate
were not a Comparable
, and you omitted the operator
modifier, comparing two dates via <
, >
, <=
, or >=
would not compile.
I couldn’t find anything in the specification on this, though. However in a polymorphic sense it makes sense – why should you be able to write a < b
where the type of a
and b
are Comparable
s, but not when they are a MyDate
? Since you wouldn’t be able to remove the “operator-ness” of this function, it makes sense that operator
should be inheritable from the superclass method.