https://kotlinlang.org logo
#getting-started
Title
# getting-started
k

Klitos Kyriacou

06/26/2022, 12:03 PM
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

Youssef Shoaib [MOD]

06/26/2022, 12:25 PM
Use a sequence:
Copy code
sequence {
  yieldAll(list1)
  yieldAll(list2)
}.firstOrNull {...}
k

Klitos Kyriacou

06/26/2022, 12:53 PM
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

Youssef Shoaib [MOD]

06/26/2022, 12:56 PM
Even better would maybe be defining `plus`for sequences and then just doing
(list1.asSequence() + list2).asIterable()
k

Klitos Kyriacou

06/26/2022, 1:03 PM
That's nice too (though the asymmetry of calling
asSequence
on only one of the lists makes the code less elegant)
y

Youssef Shoaib [MOD]

06/26/2022, 1:15 PM
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

Klitos Kyriacou

06/26/2022, 1:24 PM
The plus method is implemented using flatten anyway.
y

Youssef Shoaib [MOD]

06/26/2022, 1:30 PM
Oh I didn't even realise that was the underlying implementation lol! Yeah definitely go with the flatten solution then
👍 1
n

nkiesel

06/26/2022, 6:31 PM
We have a flatMap as convenience for .map{}.flatten(), so having a flatSequenceOf might be nice
5 Views