Naive implementation of Either in JAva
package bad.robot; | |
import fj.F; | |
import java.util.function.Function; | |
import java.util.stream.Stream; | |
public interface Either<A, B> { | |
static <A, B> Either<A, B> left(final A a) { | |
return new Left<>(a); | |
} | |
static <A, B> Either<A, B> right(final B b) { | |
return new Right<>(b); | |
} | |
static <T, R> Function<T, Either<Pair<T, Throwable>, R>> asEithers(Function<T, R> function) { | |
return (T a) -> { | |
try { | |
return Either.<Pair<T, Throwable>, R>right(function.apply(a)); | |
} catch (Throwable e) { | |
return left(Pair.pair(a, e)); | |
} | |
}; | |
} | |
Boolean isLeft(); | |
Boolean isRight(); | |
Stream<A> left(); | |
Stream<B> right(); | |
class Left<A, B> implements Either<A, B> { | |
private final A value; | |
public Left(A value) { | |
this.value = value; | |
} | |
@Override | |
public Boolean isLeft() { | |
return true; | |
} | |
@Override | |
public Boolean isRight() { | |
return false; | |
} | |
@Override | |
public Stream<A> left() { | |
return Stream.of(value); | |
} | |
@Override | |
public Stream<B> right() { | |
return Stream.empty(); | |
} | |
} | |
class Right<A, B> implements Either<A, B> { | |
private final B value; | |
public Right(B value) { | |
this.value = value; | |
} | |
@Override | |
public Boolean isLeft() { | |
return false; | |
} | |
@Override | |
public Boolean isRight() { | |
return true; | |
} | |
@Override | |
public Stream<B> right() { | |
return Stream.of(value); | |
} | |
@Override | |
public Stream<A> left() { | |
return Stream.empty(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment