I want to do `String? -> Validated<E, String...
# arrow
e
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
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
Ah, that's more elegant. Thank you 🙌