简体   繁体   English

如何使用Kotlin中的现有比较器

[英]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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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