Introduce reversed extension for Comparator.

This commit is contained in:
Ilya Gorbunov
2015-08-26 16:49:44 +03:00
parent 5a474adf59
commit b8badd59ba
2 changed files with 18 additions and 2 deletions
+12 -1
View File
@@ -315,4 +315,15 @@ public fun <T: Comparable<T>> nullsLast(): Comparator<T?> {
return a.compareTo(b)
}
}
}
}
/** Returns a comparator that imposes the reverse ordering of this comparator. */
public fun <T> Comparator<T>.reversed(): Comparator<T> = when (this) {
is ReversedComparator -> this.comparator
else -> ReversedComparator(this)
}
private class ReversedComparator<T>(public val comparator: Comparator<T>): Comparator<T> {
override fun compare(a: T, b: T): Int = comparator.compare(b, a)
}