Convert [Test [E, A]] to Test [E, Option [A]]

In ScalaZ, what is the idiomatic way to convert Option[Validation[E, A]] to Validation[E, Option[A]] ?

For example, in the following hypothetical code:

 def convert(x: Option[Validation[E, A]]): Validation[E, Option[A]] = /* ??? */ def validateThing(thing: A): Validation[E, A] = /* whatever */ def exampleUseCase(maybeThing: Option[Thing]): Validation[E, Option[Thing]] = { val validated: Option[Validation[E, Thing]] = a.map(validateThing(_)) // ... val result: Validation[E, Option[Thing]] = convert(validated) result } 

What will be the implementation of convert in idiomatic ScalaZ?

+5
source share
1 answer

Here I see two possible solutions. Probably the easiest one using pattern matching in the argument, for example:

 def convert[A](v: Option[Validation[Throwable, A]]): Validation[Throwable, Option[A]] = { v match { case None => Validation.success(None) case Some(valid) => valid.map(Some(_)) } } 

For a Scalaz-based solution, I was thinking about consistency , so you need to use ValidationNel instead of checking, to aggregate possible problems, you can implement convert with Traversable :

 def convert[A](v: Option[ValidationNel[Throwable, A]]): ValidationNel[Throwable, Option[A]] = Traverse[Option].sequenceU(v) 

Please note that in fact I use sequenceU instead of just sequence , it is nothing but Scalaz's internal magic for the correct type inference, because validation has two types of parameters. Hope this helps.

+4
source

Source: https://habr.com/ru/post/1243177/


All Articles