如何根据Option值返回Either的Left/Right?Java8+Vavr编译报错求助
解决Vavr Option转Either的类型不匹配问题
首先看你的报错,核心问题是**orElse方法的返回类型不匹配**。你用map把Option<Integer>转换成了Option<Either<String, Integer>>,但orElse要求你返回的是Option<? extends Either<...>>(或者Supplier提供这个类型),但你的lambda直接返回了Either,这就导致编译器报错了。
最简洁的解决方案:用Option.toEither()
Vavr的Option本身就提供了直接转Either的方法,一行就能搞定,完全不需要写map和orElse:
public Either<String, Integer> doSomething() { Optional<Integer> optionalInteger = Optional.of(Integer.MIN_VALUE); Option<Integer> integerOption = Option.ofOptional(optionalInteger); return integerOption.toEither("Error message"); }
带额外逻辑的解决方案:用Option.fold()
如果需要在存在值的时候执行额外操作,或者在空值的时候做额外检查,那可以用fold方法——这是Vavr处理这类分支逻辑的常用方式,完全避免嵌套:
public Either<String, Integer> doSomething() { Optional<Integer> optionalInteger = Optional.of(Integer.MIN_VALUE); Option<Integer> integerOption = Option.ofOptional(optionalInteger); return integerOption.fold( // None分支:执行你的额外检查,返回Left () -> { // 此处执行其他检查逻辑 return Either.left("Error message"); }, // Some分支:执行你的其他操作,返回Right value -> { // 此处执行其他操作,比如验证value、转换等 return Either.right(value); } ); }
为什么原来的写法不行?
再回头看你的代码:
return integerOption.map(value -> { return Either.right(value); }).orElse(() -> { return Either.left("Error message"); });
map之后得到的是Option<Either<String, Integer>>,而orElse的参数如果是Supplier的话,必须返回Option<? extends Either<...>>,但你的lambda返回的是Either,不是Option<Either>,所以编译器报错说“返回类型不匹配”。如果非要用orElse的话,你需要把返回的Either包进Option里,但这样最后还要再unwrap,完全没必要,不如直接用fold或者toEither。
内容的提问来源于stack exchange,提问作者EFOE
相关产品推荐
相关产品推荐

