Hey team, How can I flatten List<Either<Exc...
# arrow
s
Hey team, How can I flatten List<Either<Exception, Value>> to List<Value>??
j
The method you are looking for is
sequence
from the
Traverse
typeclass. We have quite good docs for this typeclass it is well worth a read: https://arrow-kt.io/docs/0.10/apidocs/arrow-core-data/arrow.typeclasses/-traverse/
For you method in particular you can do
sequence(Either.applicative()).fold({ emptyList() }, ::identity)
(might need some type parameters though)
s
Awesome. Thanks for the quick help. I will check the document and implement it. ๐Ÿ‘๐Ÿ‘
One quick question, what if one of the Result in the List have an exception? Can I still return the List with valid data?
@Jannis
j
ah,
sequence
will use
ap
to combine the
Either
's in the list. This means it will short circuit on a
Left
. Note that it returns
Either<E, List<A>>
. If you want to concatenate all values ignoring failure you can use
filterMap
instead to do something like this:
filterMap { it.toOption() }
๐Ÿ‘ 1
s
Ohh! Got it! I forgot that I could have used filterMap..thanks a lot ๐Ÿ‘
Just a long tiring day and brain has stopped working ๐Ÿ˜‚
j
Just an observation, I've been lurking this group for over a month and I've seen this question asked 5 times (I've also asked it myself). Is there a FAQ?
๐Ÿ‘ 1
๐Ÿ˜‚ 1
270 Views