我有 scalaz Validation 的这个实现,似乎隐式 scalaz.Bind 不在范围内,所以 for 表达式不起作用。
这是代码:
import scalaz._
import Scalaz._
case class User(name: String, knowScala: Boolean, age: Int)
object PublicValidationSpec extends BasicValidation {
def validate(user: User): Validation[String, String] = {
for {
b <- checkAge(user)
c <- checkName(user)
} yield s"Congrats, ${c.name}"
}
}
trait BasicValidation {
def checkName(user: User): Validation[String, User] = {
if(user.name == "") "must have a name".fail else user.success
}
def checkAge(user: User): Validation[String, User] = {
if(user.age < 3) "must be a valid age".fail else user.success
}
}
异常(exception)是
Error:(14, 25) Implicit not found: scalaz.Unapply[scalaz.Bind,
scalaz.Validation[String,scalaz.validation.User]]. Unable to unapply type
`scalaz.Validation[String,scalaz.validation.User]` into a type constructor of
kind `M[_]` that is classified by the type class `scalaz.Bind`. Check that the
type class is defined by compiling `implicitly[scalaz.Bind[type constructor]]` and
review the implicits in object Unapply, which only cover common type 'shapes.'
b <- checkAge(user)
Did i miss some implicit imports here ?
^
最佳答案
验证没有为其定义绑定(bind)。
在 Scalaz 7.1.0-M5(M6 也是)Validation.flatMap
已弃用,并试图破坏警告,它看起来像 flatMap
的优先级正在输给 scalaz.syntax.bind._
,它是 Scalaz._
的一部分进口。查看此提交 https://github.com/scalaz/scalaz/commit/2727b2451eba2aa159f3fbb62bf92790ac99dc7a .尝试添加 import scalaz.Validation.FlatMap._
或仅导入您需要的东西,例如
import scalaz.Validation
import scalaz.syntax.validation._
我建议使用
Validation
之外的其他东西但是,因为这可能只会在将来给您带来更多问题。见 scalaz.\/
以下。这确实与 scalaz 7.0.5 一起编译。
Validation.flatMap
在 7.0.6 中定义,因此它也应该使用该版本进行编译。不过,我不会在新代码中使用此功能(Validation
中的 for
理解)。scalaz 的权力在弃用
Validation.flatMap
时来回走动已经有一段时间了。 flatMap
是什么让它在 for
中工作理解。 flatMap
is deprecated in the working branch though .这有很长的背景。见 https://groups.google.com/forum/#!topic/scalaz/Wnkdyhebo2w .TLDR - 验证不是单子(monad)。
Validation.flatMap
的任何可能实现与 Apply
的行为不匹配为 Validation
定义.使用
scalaz.\/
(a.k.a. disjunction) 如果你想在 for
中使用某些东西理解。如果需要累积错误,使用Validation
的原因超过 \/
, 转换为 Validation
然后返回 \/
.
关于验证:未找到隐式 scalaz.Bind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22635033/