1
votes

I want to flat map a Collection of Sets to a single Set. I have the following code which does not compile in IntelliJ IDEA. I can't tell why:

listOf(HashSet<String>()).flatMapTo(HashSet<String>()) { it.iterator() as Iterator<String> }

There is a very confusing error message on the lambda in the end which says:

Type mismatch. Required: (kotlin.collections.HashSet<String> /* = java.util.HashSet<String> /) → Iterable<String> Found: (kotlin.collections.HashSet<String> / = java.util.HashSet<String> */) → Iterator<String>

But they are both completely the same? I am confused as to why that doesn't want to work.

There is also an error message shown on the flatMapTo function and says:

Type inference failed:

inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapTo ( destination: C, transform: (T) → Iterable<R> ) : C cannot be applied to

receiver: List<kotlin.collections.HashSet<String> /* = java.util.HashSet<String> &ast;/> arguments: ( kotlin.collections.HashSet<String> /* = java.util.HashSet<String> &ast;/, (kotlin.collections.HashSet<String> /* = java.util.HashSet<String> &ast;/) → Iterator<String> )

*Hope I didn't forget any special characters in the quotes. had to replace < and some * with html entities.*

1

1 Answers

2
votes

Your lambda returns an Iterator<String>. It's supposed to return an Iterable<String>. A Set<String> is already an Iterable<String>.

All you need is

listOf(HashSet<String>()).flatMapTo(HashSet()) { it }