这是我之前的question:
的后续内容假设我需要验证数据结构(例如XML,JSON,HttpRequest等)。我可以定义一个验证函数A => ValidationNel[String, B]
和一个包装类:
class Validate[A, B](run: A => ValidationNel[String, B]) {
def apply(a: A) = run(a)
}
我还将方法andThen
和andAlso
添加到撰写 Validates
:
def andThen[C](other: Validate[B, C]) = new Validate[A, C] {a =>
this(a) flatMap (b => other(b))
}
def andAlso(other: Validate[A, B]) = new Validate[A, B] (a =>
(this(a), other(a)) match {
case ((Success(b), Success(b)) => Success(b)
case (failure @ Failure(errors), Success(b)) => failure
case (Success(b), failure @ Failure(errors)) => failure
case (Failure(errors1), Failure(errors2)) => Failure(errors1 + errors2)
}
)
现在我可以按如下方式验证数据结构:
case class Header(...)
case class Payload(...)
case class Message(header: Header, payload: Payload)
val validateHeader: Validate[Header, Header] = ...
val validatePayload: Validate[Payload, Payload] = ...
type ValidateMessage = Validate[Message, Message]
val validateMessageHeader =
new ValidateMessage(m => validateHeader(m.header); m)
val validateMessagePayload =
new ValidateMessage(m => validatePayload(m.payload); m)
val validateMessage = validateMessageHeader andAlso validateMessagePayload
有意义吗?您如何建议修复/改进它?