Created
August 14, 2016 13:03
-
-
Save afcastano/604ac9cb72a0aae9fbeb0e2d78ccb9d9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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