thenByDescending所在位置是kotlin.comparisons.thenByDescending,其相关用法介绍如下。

用法一

inline fun <T> Comparator<T>.thenByDescending(
    crossinline selector: (T) -> Comparable<*>?
): Comparator<T>

使用主比较器和将值转换为 Comparable 实例以进行比较的函数创建一个降序比较器。

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val list = listOf("aa", "b", "bb", "a")

val lengthComparator = compareBy<String> { it.length }
println(list.sortedWith(lengthComparator)) // [b, a, aa, bb]

val lengthThenStringDesc = lengthComparator.thenByDescending { it }
println(list.sortedWith(lengthThenStringDesc)) // [b, a, bb, aa]
//sampleEnd
}

输出:

[b, a, aa, bb]
[b, a, bb, aa]

用法二

inline fun <T, K> Comparator<T>.thenByDescending(
    comparator: Comparator<in K>, 
    crossinline selector: (T) -> K
): Comparator<T>

在主比较器定义它们相等之后,创建一个降序比较器比较值。它使用 selector 函数来转换值,然后将它们与给定的 comparator 进行比较。

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val list = listOf("A", "aa", "b", "bb", "a")

val lengthComparator = compareBy<String> { it.length }
println(list.sortedWith(lengthComparator)) // [A, b, a, aa, bb]

val lengthThenCaseInsensitive = lengthComparator
    .thenByDescending(String.CASE_INSENSITIVE_ORDER) { it }
println(list.sortedWith(lengthThenCaseInsensitive)) // [b, A, a, bb, aa]
//sampleEnd
}

输出:

[A, b, a, aa, bb]
[b, A, a, bb, aa]