Scala with Cats练习:Kleisli数据验证为何快速失败不累积错误
问题根源
你在createUser方法中直接使用Either类型的返回值做mapN组合,而Either的Semigroupal实现是快速失败的:只要第一个校验(用户名)返回Left,第二个校验(邮箱)的结果会被直接忽略,不会做错误合并。只有Validated类型的Semigroupal才会累积多个独立校验的错误。
修复方案
改动非常小,不需要调整现有校验逻辑,只需修改两点:
- 增加
either语法的导入:
import cats.syntax.either._
- 修改
createUser方法,将两个Either结果先转为Validated做错误累积组合,再转回Either即可:
def createUser(username: String, email: String): Either[Errors, User] = (checkUsername.run(username).toValidated, checkEmail.run(email).toValidated).mapN(User).toEither
效果验证
修改后运行main方法,输出会符合预期:
Left(NonEmptyList(Must be longer than 3 characters, Must contain a single @ character))
内容的提问来源于stack exchange,提问作者SkyOne
相关产品推荐
相关产品推荐

