2

我正在尝试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>>)
4

3 回答 3

7

orElseOption<T>当返回doSomething类型需要时返回Either<String, Integer>

相反,尝试使用getOrElsewhich 返回T

public Either<String, Integer> doSomething() {
    // ...
    return integerOption.map(
        Either::<String, Integer>right).getOrElse(
            () -> Either.left("Error message"));
}
于 2019-06-08T21:34:55.127 回答
0

既然你想返回Either<...>不是Option<Either<...>>你必须使用getOrElse

于 2019-06-08T21:45:11.490 回答
0

我认为@oleksandr-pyrohov 的答案中多余的泛型和格式使事情变得过于复杂。我只是这样写:

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

更新。:虽然它似乎并不总是很遗憾地推断出它自己的泛型。

于 2020-06-04T14:45:32.057 回答