What would be an idiomatic way to create Either if...
# arrow
i
What would be an idiomatic way to create Either if I am not assigning it to a variable so I can't specify its exact type. To be more precise, I am trying to convert a Result to Either. If Result is Ok want to give that value to right, if Results contain a Throwable I set left to sam error. Code is something like this:
Copy code
fun <T : Any> Result<T>.toEither(): Either<RequestError, T> =
    fold({ Either.right(it)}, {Either.left(calculateError())})
However, this doesn't compile (although Intellij doesn't show that anything is wrong with the code), as
Either.right
creates
Either<Nothing, T>
and
Either.left
creates
Either<T, Nothing>
, so neither branching of the fold returns the needed type. Can I create wanted Either here (without having to create it with val, specify its exact type and returning that). I hoped simply doing something like
Either<RequestError, T>.right
would work, but of course it doesn't 😄
r
Try inverting the order of arguments in your fold function
sorry didn't realized it was fold from Result
Perhaps it's easier to just use the Boolean operators
If isSuccess..
i
I can do it like that. Is this situation (not having an easy way to create Either in single line) a design choice or something that might be changed in the future? As far as I can see, technically I could do it with Either.cond but I don't know how nicely that would play with Result
p
hint the types
if this is what I think it is, it’s just the kotlin compiler failing to infer the type of two lambdas that converge because they check them in order, and the first one has incomplete types
Copy code
fold({ 
val a: Either<RequestError, T> = Either.right(it)
a
}, {Either.left(calculateError())})
see if that works