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
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 <.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With