My question is somewhat related to Kotlin arrow-kt Flatten nested Either, but also not exactly.
I have a list that I map through, and within this map I call a function that returns an Either. If the Either contains an error, I need to quit right away.
I currently have something like this:
fun doSomethingWithUsers(userList: List<User>): Either<SomethingBadException, List<User>> =
userList
.map {
if (!isAlreadyProcessed(it)) {
processUser(it.userId).fold(
ifLeft = {
somethingBadException -> return@doSomethingWithUsers Either.Left(somethingBadException)
},
ifRight = { processedUser ->
User.createUser(processedUser)
}
)
} else it
}.let { Either.Right(it) }
Is there an alternative to the return@
?
Is there a better more idiomatic way to do this?
I'm currently on v0.8.2 of arrow-kt , but I might be able to update to 1.0.1
Thank you.
You can use traverseEither
to achieve that.
fun processUser(user: User): Either<Error, User> = TODO()
val list: List<User> = TODO()
list.traverseEither { processUser(it) } // Either<Error, List<User>>
For older arrow versions try:
list.traverse(Either.applicative(), { processUser(it) }).fix()