javafixes.object.changing.FailableValue Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of javafixes Show documentation
Show all versions of javafixes Show documentation
Things I would like to have in Java by default
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 super T> 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