【问题标题】:Kotlin: Higher Order Function : sortedWith()Kotlin:高阶函数:sortedWith()
【发布时间】:2021-05-10 16:14:44
【问题描述】:

我正在尝试从基本的 android kotlin codelabs here 学习 kotlin,其中 codelabs 解释了 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

【问题讨论】:

  • 更新你的 kotlin 版本到 1.4.30
  • 链接的 Kotlin Playground 使用 Kotlin 1.4.30,而您显然仍在使用 Kotlin 1.3。 (旁注:1.3.50 到现在已经相当老了,特别是考虑到 Kotlin 接收更新/功能的速度。可能值得升级到 1.4。)自 Kotlin 1.3 以来,类型推断有 changed a lot(尽管它仍然可以在1.3,我相信)。

标签: android kotlin


【解决方案1】:

使用 compareBy

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

输出

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

【讨论】:

  • 当我将 IntelliJ IDEA 中的 kotlin 语言版本和 api 版本从 1.3 更改为 1.4 时,它起作用了。谢谢顺便说一句.. :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-04
  • 2018-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多