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

Mat*_*att 4 lambda kotlin functional-interface

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

myStringIterable.toSortedSet({a,b -> a.compareTo(b)}) 
Run Code Online (Sandbox Code Playgroud)

然而,这似乎不起作用。错误说

类型不匹配。必需的 kotlin.Comparator <String>

找到:(String,String) -> Int

Comparator 是一个Functional Interface,所以我应该能够将它作为 Lambda 传递,不是吗?

s1m*_*nw1 5

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

toSortedSet(compareBy { it.length })
Run Code Online (Sandbox Code Playgroud)

我认为在你的情况下,toSortedSet虽然没有必要争论。


yol*_*ole 4

从 Kotlin 1.2 开始,仅 Java 接口支持 SAM 转换。kotlin.Comparator是 Kotlin 中定义的接口,对于此类接口,不支持将 lambda 转换为这些接口的实现。