Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Can't Kotlin Infer The Type For Comparator

Reading the Java interop document about SAM Conversions, I expected the Kotlin function

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

to be able to take a lambda function without needing to explicitly specify the parameter is a Comparator. However the following code gives type inference failed:

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

whereas:

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

compiles and runs correctly

like image 413
matt freake Avatar asked Sep 12 '18 09:09

matt freake


1 Answers

After reading the comments from the Kotlin issue 'SAM for Kotlin classes' I learned a lot regarding the SAM conversion and why typealias was introduced, but not yet why this specific behaviour wasn't solved yet... and I am not the only one as the issue and its comments show.

Summarizing, the SAM conversion was only considered for Java interfaces (compare also 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 or both.

By the way: a very similar example was also used by Ilya Gorbunov using arrayOf().sort.

like image 65
Roland Avatar answered Sep 30 '22 08:09

Roland