Is there a Kotlin convenience function that allows...
# getting-started
k
Is there a Kotlin convenience function that allows me to combine multiple Iterables into a single Iterable? In other words, can I do something like this:
Copy code
(list1 + list2).firstOrNull { it.matches(something) }
but without eagerly iterating the lists and creating a new list from them? In other words, exactly like Guava's
FluentIterable.concat(list1, list2)
but more Kotlin-idiomatic?
y
Use a sequence:
Copy code
sequence {
  yieldAll(list1)
  yieldAll(list2)
}.firstOrNull {...}
k
Thanks.
sequenceOf(list1, list2).flatten()
is even a little bit shorter. If I wanted the exact behaviour of
FluentIterable.concat
I would have to add
.asIterable()
. It's just a little bit disappointing that
sequenceOf(list, list2).flatten().asIterable()
is longer than
FluentIterable.concat(list1, list2)
but most of the time I can take it directly as a Sequence, so I can omit the
.asIterable()
.
y
Even better would maybe be defining `plus`for sequences and then just doing
(list1.asSequence() + list2).asIterable()
k
That's nice too (though the asymmetry of calling
asSequence
on only one of the lists makes the code less elegant)
y
You could call it on both as well, but it'll just be a bit redundant. The `flatten`solution is neat though, even if it technically results in like one extra sequence being created lol
k
The plus method is implemented using flatten anyway.
y
Oh I didn't even realise that was the underlying implementation lol! Yeah definitely go with the flatten solution then
👍 1
n
We have a flatMap as convenience for .map{}.flatten(), so having a flatSequenceOf might be nice