Created
August 5, 2016 16:05
-
-
Save benhardy/112642313026040d274117c02b059132 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* I know Either is a well known class in Scala, but I'm wondering if I've stumbled onto a well known pattern with this | |
* extract() function? | |
*/ | |
public static final class Either<A,B> { | |
private final A left; | |
private final B right; | |
public boolean ifLeft(@Nonnull Consumer<A> todo){ | |
if (left != null) { | |
todo.accept(left); | |
return true; | |
} | |
return false; | |
} | |
public boolean ifRight(@Nonnull Consumer<B> todo) { | |
if (right != null) { | |
todo.accept(right); | |
return true; | |
} | |
return false; | |
} | |
public <C> C extract(@Nonnull Function<A,C> extractLeft, @Nonnull Function<B,C> extractRight) { | |
if (left != null) { | |
return extractLeft.apply(left); | |
} | |
return extractRight.apply(right); | |
} | |
static <X> Either<X, ?> left(@Nonnull X a) { | |
return new Either<>(a, null); | |
} | |
static <Y> Either<?, Y> right(@Nonnull Y b) { | |
return new Either<>(null, b); | |
} | |
/** use static factories left() and right() */ | |
private Either(A a, B b) { | |
this.left = a; | |
this.right = b; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment