In Kotlin comparison operators can be used instead of compareTo method:
a > b // a.compareTo(b) > 0
a < b // a.compareTo(b) < 0
a >= b // a.compareTo(b) >= 0
a <= b // a.compareTo(b) <= 0
It's convenient and makes comparisons a lot more readable. However, these operators cannot be used if there is no suitable compareTo method, but there is a suitable Comparator.
To make it possible to use them in this case, I've created a use extension function for a Comparator interface:
inline fun <T, R> Comparator<T>.use(block: ComparatorDSL<T>.() -> R) =
ComparatorDSL(this).run(block)
Where ComparatorDSL is the following class:
inline class ComparatorDSL<T>(private val comparator: Comparator<T>) {
operator fun T.compareTo(other: T) = comparator.compare(this, other)
}
Now I can use it like this:
comparator.use { a > b } // comparator.compare(a, b) > 0
Questions:
- Is
comparator.use { a > b }more readable thancomparator.compare(a, b) > 0? - Is it a good idea to replace
usewithinvokeoperator or make this functioninfix? - Any improvement suggestions that you can think of
checkdoesn't make much sense if you use it not for one comparison but wrap the whole function with it. Maybe it's better to remove the name completely and use theinvokeoperator. \$\endgroup\$