Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 907
Jan B. Avatar asked Dec 17 '22 21:12

Jan B.


2 Answers

You can use compareBy to wrap code into Comparators:

toSortedSet(compareBy { it.length })

I think in your case, no argument is necessary for toSortedSet though.

like image 132
s1m0nw1 Avatar answered Jan 05 '23 10:01

s1m0nw1


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.

like image 31
yole Avatar answered Jan 05 '23 10:01

yole