Michal Patejko
03/30/2023, 11:48 AMAlejandro Serrano Mena
03/30/2023, 11:57 AMdata 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()
fun validPerson(name: String, age: Int): Either<Nel<Problem>, Person> =
either {
zipOrAccumulate(
{ validName(name).bind() },
{ validAge(age).bind() }
) { n, a -> Person(n, a) }
}
simon.vergauwen
03/30/2023, 12:10 PMvalidName
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>
.Michal Patejko
03/30/2023, 12:28 PM