我正在尝试定义验证的通用框架。我正在考虑使用部分函数来定义规则并将它们传递给通用函数以进行eval并返回结果。代码如下所示:
UIGestureRecognizer
但我无法弄清楚如何在这一行用变量参数定义部分函数参数:
def assert(name: TField, validator: PartialFunction[(Any*), String], input: Any*): Seq[ValidationError] = {
if (validator.isDefinedAt(input)) {
invalidInput(name.name, validator(input))
} else {
Seq.empty
}
}
assert(fieldA, hasValidValue, inputValue, allowedValues)
assert(fieldB, isPositive, input)
// =-=-=-=--=-=-= Validation Rules =-=-=-=-=-=-=-=
def hasValidValue[T] = PartialFunction[(T, Set[T]), String] {
case (input, validValues) if !validValues.contains(input) => "Value not allowed"
}
def isPositive = PartialFunction[Long, String] {
case value: Long if value <= 0 => "Value should always be positive"
}
所以,即使上面的定义编译得很好,但在实际尝试调用assert时会出现编译器错误:
def assert(name: TField, validator: PartialFunction[(Any*), String], input: Any*): Seq[ValidationError] = {
那么如何定义呢?
答案 0 :(得分:1)
您需要做的就是将PartialFunction[(Any*), String]
更改为PartialFunction[Seq[Any], String]
。这是因为vararg input
变为Seq[List]
,这就是验证者实际接受的内容。
这是一个关于vararg如何工作的工作演示:
case class TField(name: String)
type ValidationError = String
def invalidInput(s: String, v: String): Seq[String] = Seq(v)
def assert(name: TField, validator: PartialFunction[Seq[Any], String], input: Any*): Seq[ValidationError] = {
if (validator.isDefinedAt(input)) {
invalidInput(name.name, validator(input))
} else {
Seq.empty
}
}
def isPositive = PartialFunction[Seq[Any], String] {
case value if value.length < 2 => "Value need to have at least 2 values"
case _ => "Ok"
}
assert(TField("s"), isPositive, 5L)
assert(TField("s"), isPositive, "s1", 1, -2L, "s3")