Effective Kotlin: Item 14 —Consider implementing Comparable

Kotlin is no exception when it comes to the advantages of implementing the Comparable interface as Joshua Bloch discusses in item 14 of Effective Java.

With Kotlin we should implement kotlin.Comparable rather than java.util.Comparable. Both require the implementation of a compareTo function, but, using Kotlin’s version gives access to some extension functions. The below code shows an example compareTo function using Java 8’s comparingInt, available since Android API 24.

class Date(val year: Int, val month: Int, val day: Int) :
Comparable<Date> {

override fun compareTo(other: Date): Int {
return COMPARATOR.compare(this, other)
}

companion object {
private val COMPARATOR =
Comparator.comparingInt<Date> { it.year }
.thenComparingInt { it.month }
.thenComparingInt { it.day }
}
}

Kotlin’s extension functions allow you to use the rangeTo operator, .. to create ranges as well as coerce values within particular bounds.

fun Date.isInTwentyEighteeen(): Boolean {
return this in Date(2018, 1, 1)..Date(2018, 12, 31)
}

To make your ranges even more powerful define an iterator operator. This allows you to do for (i in Date(2017, 2, 20)..Date(2017, 3, 3)) as well as call iterator().asSequence() to be able to filter your range for example.

operator fun ClosedRange<Date>.iterator() =
object : Iterator<Date> {
var curr: Date = start

override fun
hasNext() = curr <= endInclusive
override fun
next() = curr++
}

For the above to work with the Date class example you would also need to add in an operator fun Date.inc(): Date.

Each week I am looking at “items” from Joshua Bloch’s well-respected book, Effective Java to see how it applies to Kotlin. You can find the rest of the items I’ve covered at Effective Kotlin. Please let me know your thoughts.

Matt Dolan has been eating doughnuts and developing with Android since the dark days of v1.6.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store