
本文详解如何使用 `flatmap` 正确串联多个返回 `either
在使用 Vavr 进行函数式编程时,Either
以下为修正后的完整示例:
private EithergetPath(Arg arg) { return Try.of(() -> Files.createTempFile("prefix", ".tmp")) .toEither() .mapLeft(e -> new MyError("Failed to create temp path", e)); } private Either getContent(Path path) { return Try.of(() -> Files.readString(path)) .toEither() .mapLeft(e -> new MyError("Failed to read file content", e)); } public Either handle(Arg arg) { return Either. right(arg) .flatMap(this::getPath) // 若 getPath 返回 Left,直接返回;否则提取 Path 继续 .flatMap(this::getContent); // 同理,若 getContent 失败,返回其 Left;成功则得 String }
✅ 关键原理说明:
- map(f):将 f: R → U 应用于 Right 值,结果为 Either
—— 但若 f 本身返回 Either ,则结果变为 Either >(需手动 getOrElse 或 flatMap 解包)。 - flatMap(f):要求 f: R → Either
,它自动展平,确保最终类型恒为 Either ,天然支持错误传播。
⚠️ 注意事项:
- flatMap 的函数参数必须返回 Either 类型(同左类型 L),否则编译不通过,这正是类型安全的体现;
- 所有中间步骤的 Left 均携带原始错误上下文(如 "Failed to create temp path"),无需额外处理即可透传至最终结果;
- 若需在链中添加副作用(如日志),可在 flatMap 前使用 peek(对 Right 值执行操作但不改变值)或 onLeft(对 Left 执行清理)。
总结:flatMap 是 Either 链式组合的基石。它让错误处理从“手动检查+分支”升维为声明式流水线——代码简洁、语义清晰、错误零丢失。掌握它,是写出地道 Vavr 函数式代码的第一步。










