Kotlin 对象表达式:比较器示例

Kotlin object expressions: Comparator example

此代码基本上按降序对数组进行排序:

val arrayList = arrayListOf(1, 5, 2)

Collections.sort(arrayList, object : Comparator<Int> {
   override fun compare(x : Int, y: Int) = y - x
})

y - x 覆盖比较方法究竟是如何工作的? Kotlin 怎么知道 y - x 意味着把 y 放在 x 之前 if y < x?

这其实和Kotlin无关。它与 Java API 的 Comparator 接口有关,以及 Collections.sort 如何使用它。

来自the documentation:

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

现在让我们针对您提供的论点进行尝试:

  • 1 - 5 = -4(负整数),所以 1 小于 5。
  • 5 - 2 = 3(正整数),所以 5 大于 2。
  • 等...

Collections.sort 不知道 y - x 是什么意思。它只是尊重 Comparator 接口的定义契约,任何实现者也需要尊重(如果它想要工作)。

碰巧 y - x 是一个尊重该契约的实现,因为 Math.

由于 Comparator 是一个 SAM 接口,您可以使用 lambda 更简洁地编写此代码:

Collections.sort(arrayList, {x : Int, y: Int -> y - x})

甚至

Collections.sort(arrayList) {
    x, y -> y - x
}

因为lambda是sort函数的最后一个参数,可以推断出xy的数据类型。


获取两个对象并且必须为它们定义一个整数是排序定义的抽象。您基本上可以指定这些元素在排序时的排列顺序。

对于整数排序,这似乎有点矫枉过正,但考虑到必须对更复杂的对象进行排序,例如 class Car.

的实例

这个 class 有一个 colorCode,你想按它排序:

Collections.sort(cars) {
    car1, car2 -> car1.colorCode - car2.colorCode
}

这就是您以抽象方式为这些对象定义顺序的方式。

在 Kotlin 中,您还可以使用 kotlin 集合扩展函数 sort、sorted、sortBy 等对元素进行排序

val arrayList = arrayListOf(1, 5, 2).sorted() //1,2,5

val arrayList = arrayListOf(1, 5, 2).sortedDescending() //5,2,1