Bas de Groot
08/22/2023, 5:25 PMzipOrAccumulate
. Something like this:
object MyError
fun example(input1: String, input2: String, input3: String): Either<NonEmptyList<MyError>, String> = either {
zipOrAccumulate(
{ ensure(input1.isNotBlank()) { MyError } },
{ ensure(input2.isNotBlank()) { MyError } },
{ ensure(input3.isNotBlank()) { MyError } }
) { _, _, _ ->
TODO()
}
}
Everything was smooth sailing until I encountered a model for which I need to do more than 9 validations.
I found this post on Stackoverflow, which describes the same issue for the deprecated zip
function: https://stackoverflow.com/questions/72782045/arrow-validation-more-then-10-fields/72782420#72782420
I’m not sure how to apply this to zipOrAccumulate
. Any hints on how to handle this would be greatly appreciated! 😊Youssef Shoaib [MOD]
08/22/2023, 6:45 PMBas de Groot
08/23/2023, 6:50 AMzipOrAccumulate
.
data class MyError(val name: String)
fun example(input1: String, input2: String, input3: String, input4: String, input5: String, input6: String): Either<NonEmptyList<MyError>, String> = either {
zipOrAccumulate(
{ ensure(input1.isNotBlank()) { MyError("1") } },
{ ensure(input2.isNotBlank()) { MyError("2") } },
{ ensure(input3.isNotBlank()) { MyError("3") } }
) { _, _, _ ->
zipOrAccumulate(
{ ensure(input4.isNotBlank()) { MyError("4") } },
{ ensure(input5.isNotBlank()) { MyError("5") } },
{ ensure(input6.isNotBlank()) { MyError("6") } }
) { _, _, _ ->
"$input1,$input2,$input3,$input4,$input5,$input6"
}
}
}
fun main() {
val result = example("", "two", "three", "", "", "six")
println(result)
// Actual: Either.Left(NonEmptyList(MyError(name=1)))
// Expected: Either.Left(NonEmptyList(MyError(name=1), MyError(name=4), MyError(name=5)))
}
stojan
08/23/2023, 7:56 AMzioOrAccumulate
should go as one of the inputs of the outer oneAlejandro Serrano.Mena
08/23/2023, 7:58 AMzipOrAccumulate
has a different type than the rest: the first ones use a single error, whereas the last one produces a list of errorsBas de Groot
08/23/2023, 9:02 AMAlejandro Serrano.Mena
08/23/2023, 9:18 AMNonEmptyList
everywhere, and then flatMap
at the end, something akin to
fun example(input1: String, input2: String, input3: String): Either<NonEmptyList<MyError>, String> = either {
zipOrAccumulate(
{ ensure(input1.isNotBlank()) { MyError.nel() } },
{ ensure(input2.isNotBlank()) { MyError.nel() } },
{ ensure(input3.isNotBlank()) { MyError.nel() } }
) { _, _, _ ->
TODO()
}
}.mapLeft { it.flatMap { it } }
PHaroZ
10/13/2023, 6:23 AMeither { .... }.mapLeft { it.flatMap { it } }
you could do
zipOrAccumulate(
{ err1, err2 -> err1 + err2 },
{ ensure(input1.isNotBlank()) { MyError.nel() } },
{ ensure(input2.isNotBlank()) { MyError.nel() } },
{ ensure(input3.isNotBlank()) { MyError.nel() } }
) { _, _, _ ->
TODO()
}