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

Emil Kantis

08/17/2022, 8:32 PM
I want to do
String? -> Validated<E, String> -> Validated<E, A>
(in my case converting a String? to UInt). First step is easy with
fromNullable
, but I'm not sure how to map a validated while catching.. I think I'm looking for a
mapCatching(handleError: (Throwable) -> E, f: (A) -> B)
but it doesn't seem to exist? 🙂
Copy code
inline fun <E, A, B> Validated<E, A>.mapCatching(handleError: (Throwable) -> E, f: (A) -> B): Validated<E, B> =
      fold(
         { it.invalid() },
         {
            try {
               f(it).valid()
            } catch (t: Throwable) {
               handleError(t).invalid()
            }
         },
      )
Is this bad practice?
s

simon.vergauwen

08/18/2022, 6:58 AM
Such a method, or such extension methods are definitely not considered bad practice. There is
Validated.catch
as well, and there is
andThen
.
Copy code
inline fun <E, A, B> Validated<E, A>.mapCatching(handleError: (Throwable) -> E, f: (A) -> B): Validated<E, B> =
  andThen { a -> 
     Validated.catch { f(a) }
       .handleError(handleError)
  }
e

Emil Kantis

08/18/2022, 7:15 AM
Ah, that's more elegant. Thank you 🙌
4 Views