Equal branches on an Either<> object

Issue #59 resolved
Filip Allberg created an issue

I'd like for there to be a method for the Either-class that applies the same operation on both the LHS- and the RHS-projection. One example use-case is when the Either contains two values that both implement toString() and one wants to perform some type of logging first before the distinction between the two has any logic implications.

Comments (3)

  1. Jed Wesley-Smith

    static <T> T Eithers.merge(Either<T, T> either) takes an Either with the same type on either side and return whichever one it happens to be.

    You can use <X> Either<L, R>.fold(Function<? super L, X>, Function<? super R, X>) to apply a function to either side, and given the variance annotations you can supply a Function<Object, String> in your example, for instance:

    final Either<Foo, Bar> either = …;
    final Function<Object, String> toStr = (obj) -> obj.toString;
    log.info("something interesting about this either: " + either .fold(toStr, toStr).merge());
    
  2. Log in to comment