Hi, what happen if one these option is None : ```...
# arrow
c
Hi, what happen if one these option is None :
Copy code
Option.applicative().tupled(coursOpt, eleveOpt).fix().map { tuple -> // doing stuff }.
Is there a possibility to know which one has failed ?
j
options
applicative
instance should always short-circuit and return
None
when it finds a
None
. Generally speaking the order in which this happens is undefined as
applicative
makes no assumptions about it, however I believe we have a convention that unless explicitly noted the order is always left to right. This is somewhat important for things like
traverse
. Knowing which failed is not possible with
Option
because
None
carries no information with it, consider using a type that has a custom error like
Either
or similar. Figuring out where something went short-circuit in an
Applicative
combinator is usually the wrong approach (because the order is just by convention), do you want to recover in those cases or just for the error message?
c
In my case I just want to throw an error message. The 2 optionals come from requests from the database and I do some verifications with these 2 values. If one them is None, I want to throw the appropriate error message.
Is there any alternative to handle this ?
j
you could to something like
Either.applicative().tupled(a.toEither { "MyErr1" }, b.toEither { "MyErr2" })
This will return a
Either<String, Tuple2<...>>
which you can then fold to get the error or the value. Note this will not combine errors if both fail, if you want that you'd need
Validated
instead of error, but the idea is the same
👍🏾 1
k
Can definitely recommend using Validated for this pattern. https://arrow-kt.io/docs/0.10/apidocs/arrow-core-data/arrow.core/-validated/