Un type pour une valeur ou une erreur

import java.util.Optional;

public abstract class Validation<E, T> {

    private Validation() {}

    abstract Validation<T, E> swap();

    abstract Optional<T> toOptional();

    public static class Success<E, T> extends Validation<E, T> {
        private final T value;

        public Success(T value) {
            this.value = value;
        }

        @Override
        Failure<T, E> swap() {
            return new Failure<>(value);
        }

        @Override
        public Optional<T> toOptional() {
            return Optional.ofNullable(value);
        }

    }

    public static class Failure<E, T> extends Validation<E, T> {

        private final E error;

        public Failure(E error) {
            this.error = error;
        }

        @Override
        Optional<T> toOptional() {
            return Optional.empty();
        }

        @Override
        Success<T, E> swap() {
            return new Success<>(error);
        }

    }
}

About fifcan

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!