为什么 Kotlin 不能推断比较器的类型

Why Can't Kotlin Infer The Type For Comparator

阅读关于 SAM Conversions 的 Java 互操作文档,我期待 Kotlin 函数

Collections.sortWith(comparator: kotlin.Comparator<in T> /* = java.util.Comparator<in T> */)

能够在不需要显式指定参数的情况下采用 lambda 函数是比较器。但是下面的代码给出 type inference failed:

val someNumbers = arrayListOf(1, 5, 2)
someNumbers.sortWith({ x, y -> 1 })

鉴于:

val someNumbers = arrayListOf(1, 5, 2)
someNumbers.sortWith(Comparator { x, y -> 1 })

正确编译和运行

阅读 Kotlin issue 'SAM for Kotlin classes' 的评论后,我了解了很多关于 SAM 转换以及引入 typealias 的原因,但还不知道为什么这个特定行为还没有解决...和正如问题及其评论所示,我不是唯一一个。

总而言之,SAM 转换仅考虑用于 Java 接口(也比较 this comment). Jetbrains did work on (or still needs to do) a bigger refactoring and tries to solve that issue so that SAMs are also available for Kotlin functions themselves (compare also this comment). They are trying to support SAM conversion for kotlin functions in a separate issue, which could come with 1.3. As I am currently testing 1.3: I did not see anything regarding this yet. So maybe, if you like the SAM conversion as I do, you may want to upvote either SAM for Kotlin classes or SAM conversion for kotlin function 或两者。

顺便说一句:a very similar example was also used by Ilya Gorbunov using arrayOf().sort.