package com.hbm.util; import java.util.function.Function; /** * Represents a value that is either of generic type L or R * @author martinthedragon */ @SuppressWarnings("unchecked") public final class Either { public static Either left(L value) { return new Either<>(value, true); } public static Either right(R value) { return new Either<>(value, false); } private final Object value; private final boolean isLeft; private Either(Object value, boolean isLeft) { this.value = value; this.isLeft = isLeft; } public boolean isLeft() { return isLeft; } public boolean isRight() { return !isLeft; } public L left() { if(isLeft) return (L) value; else throw new IllegalStateException("Tried accessing value as the L type, but was R type"); } public R right() { if(!isLeft) return (R) value; else throw new IllegalStateException("Tried accessing value as the R type, but was L type"); } public L leftOrNull() { return isLeft ? (L) value : null; } public R rightOrNull() { return !isLeft ? (R) value : null; } public V cast() { return (V) value; } public T run(Function leftFunc, Function rightFunc) { return isLeft ? leftFunc.apply((L) value) : rightFunc.apply((R) value); } public T runLeftOrNull(Function func) { return isLeft ? func.apply((L) value) : null; } public T runRightOrNull(Function func) { return !isLeft ? func.apply((R) value) : null; } public T runCasting(Function func) { return func.apply((V) value); } }