All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.indeed.util.core.Either Maven / Gradle / Ivy

There is a newer version: 1.0.52-3042601
Show newest version
package com.indeed.util.core;

import com.google.common.base.Function;

/**
* @author jplaisance
*/
public interface Either {

    public  Z match(Matcher matcher) throws A;

    public  Either map(Function f);

    public  Either flatMap(Function> f);

    public B get() throws A;

    public static abstract class Matcher {

        protected Z left(A a) throws A {
            throw a;
        }

        protected Z right(B b) {
            throw new UnsupportedOperationException();
        }
    }

    public static final class Left implements Either {

        private final A a;

        public static  Either of(A a) {
            return new Left(a);
        }

        private Left(final A a) {
            this.a = a;
        }

        public  Z match(final Matcher matcher) throws A {
            return matcher.left(a);
        }

        @Override
        public  Either map(final Function f) {
            return (Either)this;
        }

        @Override
        public  Either flatMap(final Function> f) {
            return (Either)this;
        }

        @Override
        public B get() throws A {
            throw a;
        }
    }

    public static final class Right implements Either {

        private final B b;

        public static  Either of(B b) {
            return new Right(b);
        }

        private Right(final B b) {
            this.b = b;
        }

        public  Z match(final Matcher matcher) {
            return matcher.right(b);
        }

        @Override
        public  Either map(final Function f) {
            return Right.of(f.apply(b));
        }

        @Override
        public  Either flatMap(final Function> f) {
            return f.apply(b);
        }

        @Override
        public B get() throws A {
            return b;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy