Skip to content

Instantly share code, notes, and snippets.

@afcastano
Created August 14, 2016 13:03
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afcastano/604ac9cb72a0aae9fbeb0e2d78ccb9d9 to your computer and use it in GitHub Desktop.
Save afcastano/604ac9cb72a0aae9fbeb0e2d78ccb9d9 to your computer and use it in GitHub Desktop.
public class Result<T> {
private Optional<T> value;
private Optional<String> error;
private Result(T value, String error) {
this.value = Optional.ofNullable(value);
this.error = Optional.ofNullable(error);
}
/** This is the unit method */
public static <U> Result<U> ok(U value) {
return new Result<>(value, null);
}
public static <U> Result<U> error(String error) {
return new Result<>(null, error);
}
/** This is the bind method */
public<U> Result<U> flatMap(Function<T, Result<U>> mapper) {
if(this.isError()) {
return Result.error(this.error());
}
return mapper.apply(value.get());
}
public boolean isError() {
return error.isPresent();
}
public T getValue() {
return value.get();
}
public String getError() {
return error.get();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment