简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM