Reputation: 842
How do I convert a
val source: Map[MyKeyType, ValidationNel[MyErrorType, MyValueType]]
to
val target: ValidationNel[MyErrorType, Map[MyKeyType, MyValueType]]
while capturing all validation errors?
Upvotes: 3
Views: 144
Reputation: 139058
You can use sequence
to turn a type F[G[A]]
inside out (i.e., into a G[F[A]]
) if you have two things: an Applicative
instance for G
and a Traverse
instance for F
. In this case Scalaz provides both off the shelf, so you can just write source.sequenceU
(where the U
part indicates that this is a method that uses the Unapply
trick to help out Scala's type inference system).
For example:
scala> println(Map("a" -> 1.successNel, "b" -> 2.successNel).sequenceU)
Success(Map(a -> 1, b -> 2))
scala> println(Map("a" -> 1.successNel, "b" -> "BAD".failureNel).sequenceU)
Failure(NonEmptyList(BAD))
And errors will be accumulated as expected.
Upvotes: 3