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

net.yudichev.jiotty.common.lang.ResultOrFailure Maven / Gradle / Ivy

package net.yudichev.jiotty.common.lang;

import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;

import static com.google.common.base.Preconditions.checkNotNull;

public final class ResultOrFailure {
    private static final Object NO_VALUE = new Object();
    private final Either eitherResultOrFailure;

    private ResultOrFailure(Either eitherResultOrFailure) {
        this.eitherResultOrFailure = checkNotNull(eitherResultOrFailure);
    }

    public static  ResultOrFailure success(T value) {
        return new ResultOrFailure<>(Either.left(value));
    }

    public static ResultOrFailure success() {
        return new ResultOrFailure<>(Either.left(NO_VALUE));
    }

    public static  ResultOrFailure failure(String error) {
        return new ResultOrFailure<>(Either.right(error));
    }

    public void accept(Consumer resultConsumer,
                       Consumer errorConsumer) {
        eitherResultOrFailure.accept(resultConsumer, errorConsumer);
    }

    public  U map(Function resultMapper,
                     Function errorMapper) {
        return eitherResultOrFailure.map(resultMapper, errorMapper);
    }

    public Optional toSuccess() {
        return eitherResultOrFailure.getLeft();
    }

    public Optional toFailure() {
        return eitherResultOrFailure.getRight();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        ResultOrFailure other = (ResultOrFailure) obj;
        return eitherResultOrFailure.equals(other.eitherResultOrFailure);
    }

    @Override
    public int hashCode() {
        return eitherResultOrFailure.hashCode();
    }
}