Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions algebra/src/main/java/com/hubspot/algebra/Result.java
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,24 @@ public ERROR_TYPE expectErr(String message) {
return unwrapErrOrElseThrow(() -> new IllegalStateException(message));
}

/**
* Coerces the success type of an error Result to any other type.
* This is a no-op for Ok results.
* <p />
* This method helps when you need to return an error result whose success type
* doesn't match the required return type.
*
* @param <NEW_SUCCESS_TYPE> The new success type parameter
* @return A Result with the same error value but a coerced success type
* @throws IllegalStateException if called on an Ok Result
*/
public <NEW_SUCCESS_TYPE> Result<NEW_SUCCESS_TYPE, ERROR_TYPE> coerceErr() {
if (isOk()) {
throw new IllegalStateException("Cannot coerce an Ok result's success type");
}
return Result.err(unwrapErrOrElseThrow());
}

public abstract <R> R match(Function<ERROR_TYPE, R> err, Function<SUCCESS_TYPE, R> ok);

@Override
Expand Down
15 changes: 15 additions & 0 deletions algebra/src/test/java/com/hubspot/algebra/ResultTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -200,4 +200,19 @@ public void itConsumesErrors() throws Exception {
assertThat(okResults).isEmpty();
assertThat(errorResults).contains(ERR_RESULT.unwrapErrOrElseThrow());
}

@Test
public void itCoercesErr() {
Result<String, SampleError> errResult = Result.err(SampleError.TEST_ERROR);
Result<Integer, SampleError> coercedErrResult = errResult.coerceErr();

assertThat(coercedErrResult.isErr()).isTrue();
assertThat(coercedErrResult.unwrapErrOrElseThrow()).isEqualTo(SampleError.TEST_ERROR);
}

@Test(expected = IllegalStateException.class)
public void itThrowsWhenCoerceErrCalledOnOk() {
Result<String, SampleError> okResult = Result.ok(SAMPLE_STRING);
okResult.coerceErr();
}
}