I started out with something like this:
def nonEmpty[A] = (msg: String) => (a: Option[A]) => a.toSuccess(msg)
val postal: Option[String] = request.param("postal")
val country: Option[String] = request.param("country")
val params =
(postal |> nonEmpty[String]("no postal" )).toValidationNel |@|
(country |> nonEmpty[String]("no country")).toValidationNel
params { (postal, country) => ... }
Now I thought it would be nice to reduce the boilerplate for better readability and for not having to explain to more junior team members what .toValidateNel
and |@|
mean. The first thought was List
but then the last line would stop working and I'd have to give up some static safety. So I looked towards Shapeless:
import shapeless._; import poly._; import syntax.std.tuple._
val params = (
postal |> nonEmpty[String]("no postal"),
country |> nonEmpty[String]("no country")
)
params.map(_.toValidatioNel).reduce(_ |@| _)
however, I can't even seem to get past the .map(...)
bit. I've tried as per a suggestion on #scalaz:
type Va[+A] = Validation[String, A]
type VaNel[+A] = ValidationNel[String, A]
params.map(new (Va ~> VaNel) { def apply[T](x: Va[T]) = x.toValidationNel })
...to no avail.
I've asked for help on #scalaz but it doesn't seem something people just have an out of the box answer to. However, I'm really keen on learning how to solve this both for practical as well as learning purposes.
P.S. in reality my validations are wrapped inside Kleisli[Va, A, B]
so that I could compose individual validation steps using >=>
but that seems to be orthogonal to the issue as by the time that .map(...)
is reached, all Kleisli
s will have been "reduced" to Validation[String, A]
.
Poly1
as an object (for various wacky Scala-related reasons having to do with stable identifiers). This looks a lot like a traversal, and shapeless-contrib'straverse
would let you do thetoValidationNel
and (the moral equivalent of) thereduce(_ |@| _)
in one step. – Vassell