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:
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 😄