javalambdakotlincomparisoncomparator

How to use existing comparators in Kotlin


@Suppress("UNCHECKED_CAST")
val comp = Integer::compare as Comparator<Int>

Results in:

java.lang.ClassCastException:
org.organicdesign.fp.xform.TransformableTest$testToImSortedSet$comp$1
cannot be cast to java.util.Comparator

I can do this:

val comp = Comparator{ a:Int, b:Int -> Integer.compare(a, b) }

or

val comp = Comparator{ a:Int, b:Int -> a.compareTo(b) }

But is there a better way? I feel like I shouldn't have to create a new wrapper function for this.


Solution

  • You can use a function reference, and instead of

    val comp = Comparator { a: Int, b: Int -> Integer.compare(a, b) }
    

    ... just write this:

    val comp = Comparator(Integer::compare)