代码之家  ›  专栏  ›  技术社区  ›  matsev

vavr-同时使用“左”和“右”两个选项?

  •  0
  • matsev  · 技术社区  · 5 年前

    我怎样才能同时消耗一个“左”或“右”的能量呢 vavr Either 以实用的方式?

    我有一个方法返回 Either<RuntimeException, String> reportSuccess() reportFailure() . 因此,我正在寻找一个很好的,实用的方法来做这件事。如果 Either 有一个 biConsumer(Consumer<? super L> leftConsumer, Consumer<? super R> rightConsumer ,我可以这样写:

    Either<RuntimeException, String> result = // get the result from somewhere
    
    result.biConsumer(ex -> {
      reportFailure();
    }, str -> {
      repportSuccess();
    });
    

    到目前为止,我找到的最接近的解决方法是 biMap() 什么样的方法

    Either<RuntimeException, String> mappedResult = result.bimap(ex -> {
      reportFailure();
      return ex;
    }, str -> {
      reportSuccess();
      return str;
    });
    

    可以说,映射函数应该用于映射而不是副作用,所以即使它有效,我也在寻找替代方法。

    0 回复  |  直到 5 年前
        1
  •  1
  •   Nándor Előd Fekete    5 年前

    peek peekLeft

    void reportFailure(RuntimeException e) {
        System.out.println(e);
    }
    void reportSuccess(String value) {
        System.out.println(value);
    }
    
    ....
    
    // prints: some value
    Either<RuntimeException, String> right = Either.right("some value");
    right.peekLeft(this::reportFailure).peek(this::reportSuccess);
    
    // prints: java.lang.RuntimeException: some error
    Either<RuntimeException, String> left = Either.left(
        new RuntimeException("some error")
    );
    left.peekLeft(this::reportFailure).peek(this::reportSuccess);