net.optionfactory.spring.problems.Result Maven / Gradle / Ivy
package net.optionfactory.spring.problems;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Result of a computation.Can be _either_ a value or an error.
*
* @author rferranti
* @param
*/
public class Result {
private final List errors;
private final V value;
private final boolean isError;
public Result(List error, V value, boolean isError) {
this.errors = error;
this.value = value;
this.isError = isError;
}
public static Result errors(List error) {
return new Result<>(error, null, true);
}
public static Result error(Problem error) {
final List errors = new ArrayList<>();
errors.add(error);
return new Result<>(errors, null, true);
}
public static Result value(ValueType result) {
return new Result<>(new ArrayList<>(), result, false);
}
public List getErrors() {
return errors;
}
public boolean isError() {
return isError;
}
public V getValue() {
return value;
}
public Result map(Function mapper) {
if (isError) {
return Result.errors(errors);
}
return Result.value(mapper.apply(value));
}
public Result mapErrors() {
if (!isError) {
throw new IllegalStateException("cannot call mapErrors on a valued result");
}
return Result.errors(errors);
}
public static List problems(Result> first, Result>... others) {
return Stream.concat(Stream.of(first), Stream.of(others))
.flatMap(r -> r.getErrors().stream())
.collect(Collectors.toList());
}
@Override
public String toString() {
return "Result{" + "errors=" + errors + ", value=" + value + ", isError=" + isError + '}';
}
}