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

Jakub Gwóźdź

10/25/2023, 11:39 AM
Hi. Let’s say I have my Data class that can be read and then validated by some
fun 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:
Copy code
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?
y

Youssef Shoaib [MOD]

10/25/2023, 11:57 AM
You could do it all with raise:
Copy code
fun 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:
Copy code
val validatedData: Data = readInput().also { validateData(it) )
and it's immensely clearer.
j

Jakub Gwóźdź

10/25/2023, 12:03 PM
🙇 thanks that's what I was looking for