More convenient way to use comparators in Kotlin In Kotlin comparison operators can be used instead of compareTo method:

a &gt; b   // a.compareTo(b) &gt; 0
a &lt; b   // a.compareTo(b) &lt; 0
a &gt;= b  // a.compareTo(b) &gt;= 0
a &lt;= b  // a.compareTo(b) &lt;= 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 &lt;T, R&gt; Comparator&lt;T&gt;.use(block: ComparatorDSL&lt;T&gt;.() -&gt; R) =
    ComparatorDSL(this).run(block)


Where ComparatorDSL is the following class:

inline class ComparatorDSL&lt;T&gt;(private val comparator: Comparator&lt;T&gt;) {
    operator fun T.compareTo(other: T) = comparator.compare(this, other)
}


Now I can use it like this:

comparator.use { a &gt; b } // comparator.compare(a, b) &gt; 0


Questions:


Is comparator.use { a &gt; b } more readable than comparator.compare(a, b) &gt; 0?
Is it a good idea to replace use with invoke operator or make this function infix?
Any improvement suggestions that you can think of
Is comparator.use { a > b } more readable than comparator.compare(a, b) > 0?

Readability is relative and more a point of view. Usually something is considered more readable, the more people say it is.  

In my personal opinion both solutions are easy to read, while I like the syntax of the first more. Actually something very similar exists in the language already: compareBy

list.sortedWith(
  compareBy{ it.a }.thenBy { it.b }.thenByDescending { it.c }
)


It has all combinations you need and provides a nice, well readable syntax.

Is it a good idea to replace use with invoke operator or make this function infix?


use isntead of invoke


It is opinion based, just like readability. Its up to you and your team.


Infix


Making a function an infix function is just another customisation option for your syntax. The only important thing to remeber is:


  Infix function calls have lower precedence than the arithmetic
  operators, type casts, and the rangeTo operator. The following
  expressions are equivalent:
  
  
  1 shl 2 + 3 is equivalent to 1 shl (2 + 3) 
  0 until n * 2 is equivalent to 0 until (n * 2) 
  xs union ys as Set&lt;> is equivalent to xs union (ysas Set&lt;>)
  
  
  On the other hand, infix function call's precedence is
  higher than that of the boolean operators &amp;&amp; and ||, is- and
  in-checks, and some other operators. These expressions are equivalent
  as well:
  
  
  a &amp;&amp; b xor c is equivalent to a &amp;&amp; (b xor c) 
  a xor b in c isequivalent to (a xor b) in c
  


Kotlinlang.org

-

Any improvement suggestions that you can think of

Strongly consider to use compareBy like described before.