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?
You can use compareBy
to wrap code into Comparator
s:
toSortedSet(compareBy { it.length })
I think in your case, no argument is necessary for toSortedSet
though.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With