首页 > 解决方案 > kotlin 中 sortArrayWith 的源代码在哪里?

问题描述

我正在阅读这段代码并试图弄清楚 sorWith 如何使用比较器对象。函数定义如下:


    public actual fun <T> Array<out T>.sortWith(comparator: Comparator<in T>): Unit {
        if (size > 1) sortArrayWith(this, 0, size, comparator)} 

但是我无法在sortArrayWith任何地方找到源代码。我想知道它实际上是如何使用的comparator

这是上面提到的代码:


val products = arrayOf(Product("iPhone 8 Plus 64G", 850.00),
                        Product("iPhone 8 Plus 256G", 1100.00),
                        Product("Apple iPod touch 16GB", 246.00),
                        Product("Apple iPod Nano 16GB", 234.75),
                        Product("iPad Pro 9.7-inch 32 GB", 474.98),
                        Product("iPad Pro 9.7-inch 128G", 574.99),
                        Product("Apple 42mm Smart Watch", 284.93))
    
// public fun  Array.sortWith(comparator: Comparator): Unit
// -> Sorts the array in-place according to the order specified by the given [comparator].
products.sortWith(object: Comparator{
                            override fun compare(p1: Product, p2: Product): Int = when {
                                                p1.price > p2.price -> 1
                                                p1.price == p2.price -> 0
                                                else -> -1
                                            }
                  })

标签: functionkotlin

解决方案


推荐阅读