Search code examples
lambdakotlinfunctional-interface

How to pass a Lambda to toSortedSet() in Kotlin


I'm a little confused why this doesn't work. I'm having a simple Iterable of String that I want to sort via toSortedSet() my own way. I wanted to pass a lambda to it like this:

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

That, however, doesn't seem to work. The error says

Type mismatch. Required kotlin.Comparator < String>

Found: (String,String) -> Int

A Comparator is a Functional Interface, so I should be able to pass it as a Lambda, shouldn't I?


Solution

  • As of Kotlin 1.2, SAM conversion is only supported for Java interfaces. kotlin.Comparator is an interface defined in Kotlin, and for such interfaces there is no support for converting lambdas to implementations of those interfaces.