Skip to content

Instantly share code, notes, and snippets.

@PaulWoitaschek
Last active December 2, 2018 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PaulWoitaschek/7f3c4d5310a66ed4984785ee2d6f70ed to your computer and use it in GitHub Desktop.
Save PaulWoitaschek/7f3c4d5310a66ed4984785ee2d6f70ed to your computer and use it in GitHub Desktop.
Comparable selector
import java.util.*
import kotlin.comparisons.compareValuesBy
/**
* Demonstration of how the compare selectors could be moved to the companion object to prevent object allocations.
* Else each call to compareTo would create n new objects
*
* @author Paul Woitaschek
*/
class Foo(val a: String, val b: Int, val c: Date) : Comparable<Foo> {
override fun compareTo(other: Foo) = compareValuesBy(this, other, *selectors)
companion object {
val selectors: Array<(Foo) -> Comparable<*>?> = arrayOf(Foo::a, Foo::b, Foo::c)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment