gpt4 book ai didi

lambda - 如何在 Kotlin 中将 Lambda 传递给 toSortedSet()

转载 作者:行者123 更新时间:2023-12-02 07:07:53 24 4
gpt4 key购买 nike

我有点困惑为什么这不起作用。我有一个简单的 IterableString ,我想通过我自己的方式通过 toSortedSet() 进行排序。我想像这样将 lambda 传递给它:

myStringIterable.toSortedSet({a,b -> a.compareTo(b)}) 

但是,这似乎不起作用。错误提示

Type mismatch. Required kotlin.Comparator < String>

Found: (String,String) -> Int

比较器是一个函数接口(interface),所以我应该能够将它作为 Lambda 传递,不是吗?

最佳答案

您可以使用compareBy将代码包装到 Comparator 中:

toSortedSet(compareBy { it.length })

我认为在你的情况下,toSortedSet 不需要任何参数。

关于lambda - 如何在 Kotlin 中将 Lambda 传递给 toSortedSet(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51980958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com