android - 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
解决方案
使用比较
println( peopleNames.sortedWith(compareBy(
{ it.length },
{ it }
)))
输出
[Ann, Barbara, Fred, Joe]
[Ann, Joe, Fred, Barbara]
推荐阅读
- css - 如何将此引导页脚位置设置为固定在 iPad 视图中的轮播容器之后的底部?
- image-generation - 无法从图像生成器获取图像计数
- javascript - 如何在js中的复选框数组上将选中的属性设置为false
- python - Python 不读取 Excel 工作表
- android - 安卓 | 什么是 MediaStore.MediaColumns.DATA 替换?
- reactjs - react-bootstrap-table2-paginator 中的分页问题
- html - 如何为表单中动态添加的字段添加验证?
- html - 关于使用 css 和 bootstrap 的 TrinQet 程序
- node.js - 如何使用 Node js 将 csv 转换为 Json 文件?
- flutter - Flutter 从 TextField 中检索值