Skip to content

Instantly share code, notes, and snippets.

@happy-bracket
Created July 29, 2019 08:17
Show Gist options
  • Save happy-bracket/8f53035fcfe683fa7edd6bca12115ab8 to your computer and use it in GitHub Desktop.
Save happy-bracket/8f53035fcfe683fa7edd6bca12115ab8 to your computer and use it in GitHub Desktop.
Java Either, woo hoo
class JEither<L, R> {
private L left;
private R right;
private JEither() {}
public <C> C fold(Function<L, C> ifLeft, Function<R, C> ifRight) {
if (left != null) {
return ifLeft.apply(left);
} else {
return ifRight.apply(right);
}
}
public <C> JEither<L, C> mapRight(Function<R, C> map) {
return fold(JEither::Left, map.andThen(JEither::Right));
}
public <nR> JEither<L, nR> flatMapRight(Function<R, JEither<L, nR>> fmap) {
return fold(JEither::Left, fmap);
}
public static <L, R> JEither<L, R> Left(L value) {
JEither<L, R> e = new JEither<>();
e.left = value;
e.right = null;
return e;
}
public static <L, R> JEither<L, R> Right(R value) {
JEither<L, R> e = new JEither<>();
e.left = null;
e.right = value;
return e;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment