首页 > 解决方案 > Kotlin:高阶函数:sortedWith()

问题描述

我正在尝试从基本的 android kotlin codelabs here学习 kotlin ,其中一个 codelabs 解释了 lambda 和高阶函数。它显示了高阶函数的示例

排序()

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

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 操场上工作,这工作正常:这里 但是,如果我尝试在 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

标签: androidkotlin

解决方案


使用比较

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

输出

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

推荐阅读