Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Koans: Operator overloading

Tags:

kotlin

I'm completing Kotlin Koans's Comparison exercise and am wondering why compareTo() is the function being overriden but compare() is the function being used.

How do the two functions relate here?

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

fun compare(date1: MyDate, date2: MyDate) = date1 < date2
like image 819
Zorgan Avatar asked Mar 07 '26 08:03

Zorgan


1 Answers

The compare() function there just a placeholder shows "how to use compareTo()" without actual meaning. You can change it to other names as you want.

How do the two functions relate here?

A randomly named function compare() calls MyDate's compareTo() function with the comparator symbol <.

like image 120
Geno Chen Avatar answered Mar 09 '26 08:03

Geno Chen