在阅读有关SAM Conversions的Java互操作文档时,我期望使用Kotlin函数
#prepare demo data
@'
<node>
<html:productType>ABC</html:productType>
<html:productType>DEF</html:productType>
</node>
'@ | Out-File Demo.txt
cat Demo.txt | Select-String '<html:productType>(?<MyGroup>.+?)<\/html:productType>' | % {
$_.Matches[0].Groups['MyGroup'].Value
} | Out-File Demo.out
能够采用lambda函数而无需明确指定参数为Comparator。但是,以下代码给出了Collections.sortWith(comparator: kotlin.Comparator<in T> /* = java.util.Comparator<in T> */)
:
type inference failed
而:
val someNumbers = arrayListOf(1, 5, 2)
someNumbers.sortWith({ x, y -> 1 })
编译并正确运行
答案 0 :(得分:5)
阅读了Kotlin issue 'SAM for Kotlin classes'的评论后,我了解到有关SAM转换以及引入typealias
的很多知识,但还不知道为什么尚未解决此特定行为...我不是唯一的问题及其评论。
总而言之,仅将SAM转换用于Java接口(也请比较this comment)。 Jetbrains确实做了(或仍需要做)更大的重构,并尝试解决该问题,以便SAM也可用于Kotlin函数本身(也比较this comment)。他们正在尝试支持SAM conversion for kotlin functions in a separate issue,后者可能附带1.3。我目前正在测试1.3:关于此,我还没有看到任何东西。因此,也许,如果您像我一样喜欢SAM转换,则可能要同时投票SAM for Kotlin classes或SAM conversion for kotlin function或同时投票。
顺便说一句:a very similar example was also used by Ilya Gorbunov using arrayOf().sort
。