githubEdit

Unwrapping Values

How to get values out of Result objects

In essence, a Result object is just a container that wraps a success or a failure value for us. Therefore, sometimes you are going to want to get that value out of the container.

circle-info

As useful as this may seem, we will soon realize that we won't be doing it very often.

Unwrapping Success

The most basic way to retrieve the success value wrapped inside a result is by using Result::getSuccessarrow-up-right. This method will return an optional success value, depending on whether the result was actually successful or not.

@Test
void testGetSuccess() {
  // Given
  Result<?, ?> result1 = success("SUCCESS");
  Result<?, ?> result2 = failure("FAILURE");
  // Then
  Optional<?> success1 = result1.getSuccess();
  Optional<?> success2 = result2.getSuccess();
  // Then
  assertEquals("SUCCESS", success1.get());
  assertTrue(success2::isEmpty);
}

Unwrapping Failure

Similarly, we can use Result::getFailurearrow-up-right to obtain the failure value held by a Result object.

circle-check

Using Alternative Success

We can use Result::orElsearrow-up-right to provide an alternative success value that must be returned when the result is unsuccessful.

circle-info

Note that alternative success values can be null.

Mapping Failure

The Result::orElseMaparrow-up-right method is similar to Optional::orElseGetarrow-up-right, but it takes a mapping Functionarrow-up-right instead of a Supplierarrow-up-right. The function will receive the failure value to produce the alternative success value.

circle-info

Although probably not the best practice, the mapping function may return null.

Streaming Success or Failure

Finally, we can use Result::streamSuccessarrow-up-right and Result::streamFailurearrow-up-right to wrap the value held by an instance of Result into a possibly-empty Streamarrow-up-right object.

Conclusion

We explored various ways to retrieve values from results. Using these methods you can efficiently access the underlying data within a Result object, whether it's a success or a failure.

Last updated

Was this helpful?