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

javafixes.object.changing.FailableValue Maven / Gradle / Ivy

There is a newer version: 1.4.2.0
Show newest version
package javafixes.object.changing;

import javafixes.object.DataObject;
import javafixes.object.Either;
import javafixes.object.Value;

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

import static javafixes.common.util.AssertUtil.assertNotNull;
import static javafixes.object.Either.left;
import static javafixes.object.Either.right;

public class FailableValue extends DataObject implements Value {

    private final Either value;

    public FailableValue(Either value) {
        assertNotNull(value, "value", this.getClass());

        this.value = value;
    }

    public static  FailableValue wrapValue(T value) {
        return new FailableValue<>(right(value));
    }

    public static  FailableValue wrapFailure(RuntimeException exception) {
        return new FailableValue<>(left(exception));
    }

    @Override
    public T value() {
        return value
                .ifLeftThrow(e -> e)
                .getRight();
    }

    public RuntimeException failure() {
        return value
                .ifRightThrow(value -> new IllegalStateException("This value is not a failure instead it contains"))
                .getLeft();
    }

    public boolean isFailure() {
        return value.isLeft();
    }

    public boolean isNotFailure() {
        return value.isRight();
    }

    public void handleValue(Consumer valueHandler) {
        value.handleRight(valueHandler::accept);
    }

    public void handleFailure(Consumer failureHandler) {
        value.handleLeft(failureHandler::accept);
    }

    public  T2 fold(Function foldValue, Function foldFailure) {
        return value.fold(foldFailure, foldValue);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy