https://kotlinlang.org logo
#arrow
Title
m

Michal Patejko

03/30/2023, 11:48 AM
Hi, can you show me an example of how to use zipOrAccumulate method using coroutines? Just basic accumulation of 2/3 eithers and returning lefts (or all lefts merged into single object) if there's any.
a

Alejandro Serrano Mena

03/30/2023, 11:57 AM
let’s suppose you have the following scenario:
Copy code
data class Person(val name: String, val age: Int)

sealed interface Problem {
  object NameProblem
  object AgeProblem
}

fun validName(name: String): Either<NameProblem, String> = TODO()
fun validAge(age: Int): Either<AgeProblem, Int> = TODO()
then you can run both validations and accumulate any possible error by using
Copy code
fun validPerson(name: String, age: Int): Either<Nel<Problem>, Person> = 
  either {
    zipOrAccumulate(
      { validName(name).bind() },
      { validAge(age).bind() }
    ) { n, a -> Person(n, a) }
  }
s

simon.vergauwen

03/30/2023, 12:10 PM
Here
validName
and
validAge
can also be
suspend
, and
Either.zipOrAccumulate(validName(age), validAge(age)) { n, a -> Person(n, a) }
also exists. The benefit of the DSL version that Alejandro showed is that it works for both
Either<NonEmptyList<E>, A>
and
Either<E, A>
in a single DSL. Whilst with the
Either.zipOrAccumulate
version you can only combine
Either
of the same type and need to manually call
toEitherNel()
to turn
Either<E, A>
into
Either<NonEmptyList<E>, A>
.
m

Michal Patejko

03/30/2023, 12:28 PM
Thank you! So easy!
159 Views