Robert Kittilsen
05/03/2022, 12:29 AMfun getSignedUrl(fileName: String): Either<FileError, URL>
in which I Either.catch
a generation of a signed URL and mapLeft
for a potential FileError.SignedUrlError
.
In another service I have a function that looks like this: fun getReports(): Either<GeneralError, List<Report>>
. In this I’m mapping through each report and replacing filenames with a call to getSignedUrl
. I want to do it eagerly and go left on first fail.
In the end I’m folding into a HttpResponse like this: fun <BODY> Either<GeneralError, BODY>.toResponse(): HttpResponse<BODY>
As you can see I have two different Error objects and nested Either’s.
The only solution I’ve found without changing FileError.SignedUrlError
into GeneralError
is something like this:
fun <OUTER_TYPE, INNER_TYPE, ERROR_TYPE> Collection<OUTER_TYPE>.mapEitherReturningFirstLeft(block: (item: OUTER_TYPE) -> Either<ERROR_TYPE, INNER_TYPE>): Either<ERROR_TYPE, List<INNER_TYPE>> =
this.map { item ->
block(item).fold(
ifRight = { it },
ifLeft = { return it.left() }
)
}.right()
This doesn’t seem optimal. Any suggestions or thoughts will be much appreciated! 🤩simon.vergauwen
05/03/2022, 6:40 AMRobert Kittilsen
05/03/2022, 8:06 AM