Add Result.map()

This commit is contained in:
Paul Campbell 2018-06-23 18:14:19 +01:00
parent 680b6b8a0d
commit 47193e6480
4 changed files with 50 additions and 1 deletions

View file

@ -51,6 +51,11 @@ class Err<T> implements Result<T> {
return Result.error(error);
}
@Override
public <R> Result<R> map(final Function<T, R> f) {
return Result.error(error);
}
@Override
public void match(final Consumer<T> onSuccess, final Consumer<Throwable> onError) {
onError.accept(error);

View file

@ -73,12 +73,22 @@ public interface Result<T> {
* Returns a new Result consisting of the result of applying the function to the contents of the Result.
*
* @param f the mapping function the produces a Result
* @param <R> the type of the result of the mapping function
* @param <R> the type of the value withing the Result of the mapping function
*
* @return a Result
*/
<R> Result<R> flatMap(Function<T, Result<R>> f);
/**
* Applies the functions to the value of a successful result, while doing nothing with an error.
*
* @param f the mapping function to produce the new value
* @param <R> the type of the result of the mapping function
*
* @return a Result
*/
<R> Result<R> map(Function<T, R> f);
/**
* Matches the Result, either success or error, and supplies the appropriate Consumer with the value or error.
*

View file

@ -51,6 +51,11 @@ class Success<T> implements Result<T> {
return f.apply(value);
}
@Override
public <R> Result<R> map(final Function<T, R> f) {
return Result.ok(f.apply(value));
}
@Override
public void match(final Consumer<T> onSuccess, final Consumer<Throwable> onError) {
onSuccess.accept(value);

View file

@ -105,6 +105,35 @@ public class ResultTest implements WithAssertions {
assertThat(flatMap.isError()).isTrue();
}
@Test
public void success_whenMap_isSuccess() {
//given
final Result<Integer> okResult = Result.ok(1);
//when
final Result<String> result = okResult.map(value -> String.valueOf(value));
//then
assertThat(result.isOkay()).isTrue();
result.match(
success -> assertThat(success).isEqualTo("1"),
error -> fail("not an error")
);
}
@Test
public void error_whenMap_isError() {
//given
final RuntimeException exception = new RuntimeException();
final Result<Integer> errorResult = Result.error(exception);
//when
final Result<String> result = errorResult.map(value -> String.valueOf(value));
//then
assertThat(result.isError()).isTrue();
result.match(
success -> fail("not an success"),
error -> assertThat(error).isSameAs(exception)
);
}
@Test
public void useCase_whenOkay_thenReturnSuccess() {
//given