Deplant Commons Result API implements Result Pattern for Java. It is a small
Java library with a wrapper class named Result
with sealed implementations Ok
and Err
.
Idea comes from Rust std.Result crate with
some changes in API to better suite Java needs.
Made in functional style, it perfectly matches with Pattern matching techniques or more traditional conditional statements to manage results. Supports chaining results, most of the functions are lazy and don't do unnecessary work.
Library is pure Java and has no dependencies aside from test ones.
public static Result<Integer> functionCanFail(Integer i) {
return Result.of(() -> 2 / i);
}
As Result
is a sealed interface, you can pattern match it without default
branch.
var result = Result.of(() -> 8 / 0);
switch (result) {
case Ok(Integer i) when i > 2 -> System.out.println("Good!");
case Ok ok -> System.out.println("Ok: " + ok.result());
case Err err -> System.out.println("Err: " + err.error().getMessage());
}
// prints "Err: / by zero"
Results can be chained with other results through .result.mapResult( functionThatCanFail )
,
wrapped value and type can be transformed though .map( functionThatShouldntFail )
.
If you like to transpose Result<>
to Optional<>
you can do it with Result.ofOptional()
, .ok()
and .err()
methods.
Result<Integer> goodResult = Result.of(() -> 7);
Result<Integer> multipliedResult = goodResult.map(i -> i * 2); // transformations
Result<String> stringResult = goodResult.map(Object::toString); // type transformations
Result<Integer> combinedResult = goodResult.mapResult(s -> functionCanFail(s)); // transformations with other results
Integer digit = combinedResult.orElse(2); // get or default when fail
Optional<Integer> optionalDigit = combinedResult.ok(); // get as optional (empty when fail)
- OpenJDK 21 (or more)
- Gradle
dependencies {
implementation 'tech.deplant.commons:result:0.1.0'
}
- Maven
<dependency>
<groupId>tech.deplant.commons</groupId>
<artifactId>result</artifactId>
<version>0.1.0</version>
</dependency>