githubEdit

Creating Results

How to instantiate new Result objects

There are several ways to create result objects.

Successful Results

A successful result contains a non-null value produced by an operation when everything works as intended. We can use Results::successarrow-up-right to create a new instance.

@Test
void testSuccess() {
  // When
  Result<Integer, ?> result = Results.success(200);
  // Then
  assertTrue(result::hasSuccess);
  assertFalse(result::hasFailure);
}
circle-info

Note that we can invoke Result::hasSuccessarrow-up-right or Result::hasFailurearrow-up-right to check whether a result is successful or failed (more on this in the next section).

Failed Results

On the other hand, a failed result holds a value representing the problem that prevented the operation from completing. We can use Results::failurearrow-up-right to create a new one.

@Test
void testFailure() {
  // When
  Result<?, String> result = Results.failure("The operation failed");
  // Then
  assertTrue(result::hasFailure);
  assertFalse(result::hasSuccess);
}
triangle-exclamation

Results Based on Nullable Values

When we need to create results that depend on a possibly null value, we can use Results::ofNullablearrow-up-right. If the first argument is null, then the second one will be used to create a failed result.

circle-info

The second argument can be either a failure value or a function that produces a failure value.

Results Based on Optionals

We can also use Results::ofOptionalarrow-up-right to create results that depend on an Optionalarrow-up-right value. If the first argument is an empty optional, then the second one will be used to create a failed result.

circle-info

The second argument can be a Supplierarrow-up-right too.

Results Based on Callables

Finally, if we have a task that may either return a success value or throw an exception, we can encapsulate it as a result using Results::ofCallablearrow-up-right so we don't need to use a try-catch block.

circle-check

Conclusion

We've covered how to create new instances of Result using various factory methods provided by the Results class. Each method serves a specific purpose, allowing you to select the most suitable one based on the situation.

Last updated

Was this helpful?