Skip to content

Instantly share code, notes, and snippets.

@corneil
Last active August 4, 2019 09:13
Show Gist options
  • Save corneil/09d0f2948654f377b8acf908f765c823 to your computer and use it in GitHub Desktop.
Save corneil/09d0f2948654f377b8acf908f765c823 to your computer and use it in GitHub Desktop.
Kotlin extension function to use in compareTo when sorting requires multiple items.
inline fun <T> T.ifZero(exp: Int, block: T.() -> Int): Int = if (exp == 0) block() else exp
// using
data class User(
val firstName: String,
val lastName: String,
val dateOfBirth: Date
) : Comparable<User> {
// classic comparator.
override fun compareToB(other: User): Int {
var result = firstName.compareTo(other.firstName, true)
if(result == 0) {
result = lastName.compareTo(other.lastName, true)
if(result == 0) {
result = dateOfBirth.compareTo(other.dateOfBirth)
}
}
return result
}
// lambda comparator
override fun compareToA(other: User): Int =
ifZero(firstName.compareTo(other.firstName, true)) {
ifZero(lastName.compareTo(other.lastName, true)) {
dateOfBirth.compareTo(other.dateOfBirth)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment