因为errors 可能是一个空的List,并且你限制自己没有A 类型的值,我认为你不能把它写成一个总函数。要编写此类型签名,您需要通过假装空列表案例不存在来作弊,例如
def reject[A](errors: List[String]): ValidationNEL[String, A] =
Failure(errors.toNel.get) // bad!
编辑:正如 Apocalisp 指出的那样,您当然可以通过为空列表引入错误来使其成为一个整体功能。但我只会在运行时计算 errors 时这样做,而且我怀疑这不是您的用例,因为它会导致愚蠢的错误,例如:
def reject[A](errors: List[String]): ValidationNEL[String, A] =
Failure(errors.toNel getOrElse NonEmptyList("Error: There were no errors!"))
为什么不将errors 作为NonEmptyList 传递——大概只有在编译时出现错误时才使用此函数。
def reject[A](errors: NonEmptyList[String]): ValidationNEL[String, A] =
Failure(errors)
您可以通过复制NonEmptyList.apply 的签名(并将其专门化为String)来使用此简洁:
def reject[A](h: String, t: String*): ValidationNEL[String, A] =
Failure(NonEmptyList(h, t: _*))
让我们试试吧:
scala> reject("foo", "bar", "baz")
res0: scalaz.package.ValidationNEL[String,Nothing] = Failure(NonEmptyList(foo, bar, baz))