Skip to content

Instantly share code, notes, and snippets.

@Korbik
Last active October 13, 2015 06:28
Show Gist options
  • Save Korbik/4153418 to your computer and use it in GitHub Desktop.
Save Korbik/4153418 to your computer and use it in GitHub Desktop.
Implementation of Either for Google Guava
import com.google.common.base.Function;
import com.google.common.base.Optional;
import java.util.NoSuchElementException;
public abstract class Either<T, U, W> {
public abstract boolean isLeft();
public abstract boolean isRight();
public abstract U getRight();
public abstract T getLeft();
public W fold(Function<T, W> funcLeft, Function<U, W> funcRight) {
if (this.isRight()) {
return funcRight.apply(this.getRight());
} else {
return funcLeft.apply(this.getLeft());
}
}
public W apply(Function<U, W> funcRight) {
if (this.isRight()) {
return funcRight.apply(this.getRight());
} else {
return this;
}
}
public Optional<U> getOptional(){
if(this.isRight()) {
return Optional.fromNullable(this.getRight());
}else {
return Optional.absent();
}
}
}
class Left<T, U, W> extends Either<T, U, W> {
private T value;
public Left(T value) {
this.value = value;
}
@Override
public boolean isLeft() {
return true;
}
@Override
public boolean isRight() {
return !isLeft();
}
public T get() {
return value;
}
@Override
public U getRight() {
throw new NoSuchElementException("Right can't be accessed");
}
@Override
public T getLeft() {
return get();
}
}
class Right<T, U, W> extends Either<T, U, W> {
private U value;
public Right(U value) {
this.value = value;
}
@Override
public boolean isLeft() {
return false;
}
@Override
public boolean isRight() {
return !isLeft();
}
public U get() {
return value;
}
@Override
public U getRight() {
return get();
}
@Override
public T getLeft() {
throw new NoSuchElementException("Left can't be accessed");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment