興味深い抽象クラスです.

1818 ワード

public abstract class Either<L, R> implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 0l;

	private Either() { }

	@SuppressWarnings("unchecked")
	public boolean  isLeft() {
		return (this instanceof Left);
	}

	@SuppressWarnings("unchecked")
	public boolean isRight() {
		return (this instanceof Right);
	}

	public abstract L _left();
	public abstract R _right();

	public static <L, R> Either<L, R> right(final R r) {
		return new Right<L, R>(r);
	}

	public static <L, R> Either<L, R> left(final L l) {
		return new Left<L, R>(l);
	}

	private static final class Left<L, R> extends Either<L, R> implements Serializable{
		/**
		 * 
		 */
		private static final long serialVersionUID = 7066970081776250327L;
		private final L l;

		Left(final L l) {
			this.l = l;
		}

		@Override
		public L _left() {
			return l;
		}

		@Override
		public R _right() {
			return null;
		}

	}

	private static final class Right<L, R> extends Either<L, R> implements Serializable{
		/**
		 * 
		 */
		private static final long serialVersionUID = -894488879249418100L;
		private final R r;

		Right(final R r) {
			this.r = r;
		}

		@Override
		public L _left() {
			return null;
		}

		@Override
		public R _right() {
			return r;
		}

	}

}

 
 
leftかrightかハハ受け継ぐことができない...