diff --git a/algebra/src/main/java/com/hubspot/algebra/Result.java b/algebra/src/main/java/com/hubspot/algebra/Result.java index e945a2a..d1cdd65 100644 --- a/algebra/src/main/java/com/hubspot/algebra/Result.java +++ b/algebra/src/main/java/com/hubspot/algebra/Result.java @@ -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. + *

+ * This method helps when you need to return an error result whose success type + * doesn't match the required return type. + * + * @param 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 Result coerceErr() { + if (isOk()) { + throw new IllegalStateException("Cannot coerce an Ok result's success type"); + } + return Result.err(unwrapErrOrElseThrow()); + } + public abstract R match(Function err, Function ok); @Override diff --git a/algebra/src/test/java/com/hubspot/algebra/ResultTest.java b/algebra/src/test/java/com/hubspot/algebra/ResultTest.java index d9d9645..20933df 100644 --- a/algebra/src/test/java/com/hubspot/algebra/ResultTest.java +++ b/algebra/src/test/java/com/hubspot/algebra/ResultTest.java @@ -200,4 +200,19 @@ public void itConsumesErrors() throws Exception { assertThat(okResults).isEmpty(); assertThat(errorResults).contains(ERR_RESULT.unwrapErrOrElseThrow()); } + + @Test + public void itCoercesErr() { + Result errResult = Result.err(SampleError.TEST_ERROR); + Result coercedErrResult = errResult.coerceErr(); + + assertThat(coercedErrResult.isErr()).isTrue(); + assertThat(coercedErrResult.unwrapErrOrElseThrow()).isEqualTo(SampleError.TEST_ERROR); + } + + @Test(expected = IllegalStateException.class) + public void itThrowsWhenCoerceErrCalledOnOk() { + Result okResult = Result.ok(SAMPLE_STRING); + okResult.coerceErr(); + } }