I am trying to validate a list of strings sequentially and define the validation result type like that:
import cats._, cats.data._, cats.implicits._
case class ValidationError(msg: String)
type ValidationResult[A] = Either[NonEmptyList[ValidationError], A]
type ListValidationResult[A] = ValidationResult[List[A]] // not a monad :(
I would like to make ListValidationResult
a monad. Should I implement flatMap
and pure
manually or there is an easier way ?
I suggest you to take a totally different approach leveraging
cats
Validated
:It can be adapted for a generic type
T
, as per your example.Notes:
val stringList: List[String] = ???
is the list of strings you want to validate;ValidatedNel[A,B]
is just a type alias forValidated[NonEmptyList[A],B]
;evaluateString
should be your evaluation function, it is currently just an unimplemented stubif
;sequenceU
you may want to readcats
documentation about it: sequenceU;toEither
does exactly what you think it does, it converts aValidated[A,B]
to anEither[A,B]
.As @Michael pointed out, you could also use
traverseU
instead ofmap
andsequenceU