Kotlin compareTo() and comparison operators


When I want to inspect the comparison operator “<” in IDEA I found the source code defined in the primitive.kt is
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it’s less than other,
* or a positive number if it’s greater than other.
public override operator fun compareTo(other: Int): Int

but actually the return type is Boolean
val n:Boolean = a < b

I am a bit confuse here, can someone give some explanation?


This is an “operator” function, as seen by the operator flag. There is a fixed set of operator functions that can be implemented. They come with a special meaning.

In th case of compareTo operator, the special meaning is that the expression a<b will be translated by the compiler to the expression a.compareTo(b)<0.

You can also implement your own compareTo operator function, and so make the operator available for your own types.


You saved me from my confusion.THX


This correct answer.


Just addition thought…

The operator compareTo(b) is used not only for <, but all other comparing operators too. This is the reason the function defined in this way.