When exactly is the operator keyword needed in Kotlin?

In the 14th Kotlin Koan on operator overloading, I was surprised when, after solving, I looked at the answer and saw that the modifier operatorwas not what is required for the method compareTo:

data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
    override fun compareTo(other: MyDate) = when {
        year != other.year -> year - other.year
        month != other.month -> month - other.month
        else -> dayOfMonth - other.dayOfMonth
    }
}

the operator overloads the documents associated with the exercise, clearly says:

Functions that are overloaded by operators should be noted by the Modifier operator.

So what is going on here? Why is this code compiling? When is required operator?

+4
source share
2 answers

Why is this code compiling?

, Comparable<T>.compareTo 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 less than [other], or a positive number
 * if it greater than [other].
 */
public operator fun compareTo(other: T): Int

, .

operator?

operator , , , ( ..).

, foo += bar, , foo.plusAssign(bar), foo[bar] = baz foo.set(bar, baz) ..

operator , , , .

MyDate Comparable, operator, <, >, <= >= .

. - a < b, a b Comparable s, , MyDate? "" , , operator .

+3

Kotlin , . operator. , , , ..

Java, , , Comparable compareTo. Kotlin, . , <, <=, >, >= . compareTo :

obj1 > obj2obj1.compareTo(obj2) > 0

compareTo Comparable operator, .

operator , .

+3

Source: https://habr.com/ru/post/1692000/


All Articles