Kotlin:高阶函数:sortedWith()

时间:2021-02-06 14:54:48

标签: android kotlin

我正在尝试从基本的 android kotlin 代码实验室 enter image description here 中学习 kotlin,其中代码实验室解释了 lambda 和高阶函数。它显示了一个高阶函数的例子

<块引用>

sortedWith()

如果我们必须根据代码实验室中给出的字符串长度对名称列表进行排序,我们将使用此方法

fun main() {
    val peopleNames = listOf("Fred", "Ann", "Barbara", "Joe")
    println(peopleNames.sorted())
    println(peopleNames.sortedWith { str1: String, str2: String -> str1.length - str2.length })
}

上面给出的输出:

[Ann, Barbara, Fred, Joe]
[Ann, Joe, Fred, Barbara]

工作正常,如果我在 kotlin 游乐场工作:here 但是,如果我尝试在 IntelliJ IDEA 上运行此代码,则会出现错误:

Error:(37, 25) Kotlin: Type inference failed: fun <T> Iterable<T>.sortedWith(comparator: kotlin.Comparator<in T> /* = java.util.Comparator<in T> */): List<T>
cannot be applied to
receiver: List<String>  arguments: ((String, String) -> Int)
Error:(37, 35) Kotlin: Type mismatch: inferred type is (String, String) -> Int but kotlin.Comparator<in String> /* = java.util.Comparator<in String> */ was expected

我的 kotlin 版本有什么问题吗?我目前的 kotlin 版本是:

<块引用>

1.3.50-release-112

1 个答案:

答案 0 :(得分:0)

使用 compareBy

println( peopleNames.sortedWith(compareBy(
    { it.length },
    { it }
)))

输出

[Ann, Barbara, Fred, Joe]
[Ann, Joe, Fred, Barbara]