You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala with Cats练习:Kleisli数据验证为何快速失败不累积错误

问题根源

你在createUser方法中直接使用Either类型的返回值做mapN组合,而Either的Semigroupal实现是快速失败的:只要第一个校验(用户名)返回Left,第二个校验(邮箱)的结果会被直接忽略,不会做错误合并。只有Validated类型的Semigroupal才会累积多个独立校验的错误。

修复方案

改动非常小,不需要调整现有校验逻辑,只需修改两点:

  1. 增加either语法的导入:
import cats.syntax.either._
  1. 修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:45:04