Last active
August 4, 2019 09:13
-
-
Save corneil/09d0f2948654f377b8acf908f765c823 to your computer and use it in GitHub Desktop.
Kotlin extension function to use in compareTo when sorting requires multiple items.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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