common-utils/src/main/java/org/warp/commonutils/functional/OperationResult.java

76 lines
1.5 KiB
Java

package org.warp.commonutils.functional;
import java.util.Objects;
import java.util.StringJoiner;
public final class OperationResult<T> {
private final boolean cancel;
private final T value;
private OperationResult(boolean cancel, T value) {
this.cancel = cancel;
this.value = value;
}
public static <T> OperationResult<T> cancelNext(T value) {
return new OperationResult<>(true, value);
}
public static <T> OperationResult<T> result(T value) {
return new OperationResult<>(false, value);
}
public static <T> OperationResult<T> of(boolean cancel, T value) {
return new OperationResult<>(cancel, value);
}
public boolean isCancelled() {
return cancel;
}
public T getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OperationResult<?> that = (OperationResult<?>) o;
if (cancel != that.cancel) {
return false;
}
return Objects.equals(value, that.value);
}
@Override
public int hashCode() {
int result = (cancel ? 1 : 0);
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String toString() {
return new StringJoiner(", ", OperationResult.class.getSimpleName() + "[", "]")
.add("cancel=" + cancel)
.add("value=" + value)
.toString();
}
public <X> OperationResult<X> copyStatusWith(X newResults) {
if (cancel) {
return OperationResult.cancelNext(newResults);
} else {
return OperationResult.result(newResults);
}
}
}