Jakub Gwóźdź
10/25/2023, 11:39 AMfun allErrorsIn(data: Data): List<Error>
- if it returns empty list, all is ok and I want to continue processing, but if there is at least one error, I’d like to switch to Nel<Error>.left()
I have it done this way:
val incommingData : EitherNel<Error, Data> = readInput()
val validatedData : EitherNel<Error, Data> = incommingData.flatMap { data ->
val errors : List<Error> = allErrorsIn(data) // empty list means data is ok
if (errors.isEmpty) data.right() else errors.toNonEmptyListOrNull()!!
}
but I wonder if there is some nice API that does it prettier?Youssef Shoaib [MOD]
10/25/2023, 11:57 AMfun Raise<Nel<Error>>.validateData(data: Data) { allErrorsIn(Data).toNonEmptyListOrNull()?.let(this::raise) }
val incomingData: EitherNel<Error, Data> = readInput()
val validatedData: EitherNel<Error, Data> = either { data.bind().also { validateData(it) } }
It's even nicer though if you use raise everywhere because as long as you're inside a Raise<Nel<Error>>
, you can just do:
val validatedData: Data = readInput().also { validateData(it) )
and it's immensely clearer.Jakub Gwóźdź
10/25/2023, 12:03 PM