1

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.

Somaiah Kumbera
  • 7,063
  • 4
  • 43
  • 44

1 Answers1

2

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()
LordRaydenMK
  • 13,074
  • 5
  • 50
  • 56
  • Thank you @LordRaydenMK. Seems like this came out in v0.13. I'll see if I can use this after I update. If you have a suggestion for 0.8.2 as well, please let me know. – Somaiah Kumbera Jan 27 '22 at 23:53
  • 1
    @SomaiahKumbera updated my answer, it works for 0.10 so should probably work for older versions also. – LordRaydenMK Jan 28 '22 at 08:56