我试图根据选项值返回Either值。我的目标是如果存在该选项,则返回Either.right(),否则代码应返回Either.left()。
我使用Java 8和vavr 0.9.2

我想避免有条件的禁忌

public Either<String, Integer> doSomething() {
    Optional<Integer> optionalInteger = Optional.of(Integer.MIN_VALUE);
    Option<Integer> integerOption = Option.ofOptional(optionalInteger);

    return integerOption.map(value -> {
      //some other actions here
      return Either.right(value);
    }).orElse(() -> {
      //some other checks her also
      return Either.left("Error message");
    });
}


编译器失败并显示此消息

Error:(58, 7) java: no suitable method found for orElse(()->Either[...]age"))
    method io.vavr.control.Option.orElse(io.vavr.control.Option<? extends io.vavr.control.Either<java.lang.Object,java.lang.Integer>>) is not applicable
      (argument mismatch; io.vavr.control.Option is not a functional interface
          multiple non-overriding abstract methods found in interface io.vavr.control.Option)
    method io.vavr.control.Option.orElse(java.util.function.Supplier<? extends io.vavr.control.Option<? extends io.vavr.control.Either<java.lang.Object,java.lang.Integer>>>) is not applicable
      (argument mismatch; bad return type in lambda expression
          no instance(s) of type variable(s) L,R exist so that io.vavr.control.Either<L,R> conforms to io.vavr.control.Option<? extends io.vavr.control.Either<java.lang.Object,java.lang.Integer>>)

最佳答案

orElse返回Option<T>,而doSomething返回类型需要Either<String, Integer>

而是尝试使用返回getOrElseT

public Either<String, Integer> doSomething() {
    // ...
    return integerOption.map(
        Either::<String, Integer>right).getOrElse(
            () -> Either.left("Error message"));
}

10-05 21:19
查看更多