Skip to content

Instantly share code, notes, and snippets.

@mumrah
Created February 11, 2021 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mumrah/d80e24fb0ec60d21e342784324da2b3a to your computer and use it in GitHub Desktop.
Save mumrah/d80e24fb0ec60d21e342784324da2b3a to your computer and use it in GitHub Desktop.
Java implementation of Scala's Either
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
public class Either<L, R> {
private final L left;
private final R right;
private Either(L left, R right) {
if (left == null) {
Objects.requireNonNull(right);
}
this.left = left;
this.right = right;
}
public boolean isLeft() {
return left != null;
}
public boolean isRight() {
return left == null;
}
public <T> Either<T, R> mapLeft(Function<L, T> function) {
if (left != null) {
return Either.left(function.apply(left));
} else {
return Either.right(right);
}
}
public <T> Either<L, T> mapRight(Function<R, T> function) {
if (left == null) {
return Either.right(function.apply(right));
} else {
return Either.left(left);
}
}
public Optional<L> getLeft() {
return Optional.ofNullable(left);
}
public Optional<R> getRight() {
return Optional.ofNullable(right);
}
public <T> T fold(Function<L, T> leftFunction, Function<R, T> rightFunction) {
if (left != null) {
return leftFunction.apply(left);
} else {
return rightFunction.apply(right);
}
}
public void apply(Consumer<L> leftConsumer, Consumer<R> rightConsumer) {
if (left != null) {
leftConsumer.accept(left);
} else {
rightConsumer.accept(right);
}
}
public void ifLeft(Consumer<L> leftConsumer) {
if (left != null) {
leftConsumer.accept(left);
}
}
public void ifRight(Consumer<R> rightConsumer) {
if (left == null) {
rightConsumer.accept(right);
}
}
public static <L, R> Either<L, R> left(L value) {
return new Either<>(value, null);
}
public static <L, R> Either<L, R> right(R value) {
return new Either<>(null, value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment