Skip to content

Implementation of Result pattern for modern Java inspired by Rust std result crate. Perfectly suited for pattern matching.

License

Notifications You must be signed in to change notification settings

deplant/commons-result

Repository files navigation

Deplant Commons Result API

JDK version License

  • Discuss in Telegram: Channel on Telegram
  • Read full docs: javadoc

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.

Writing function that can throw

public static Result<Integer> functionCanFail(Integer i) {
    return Result.of(() -> 2 / i);
}

Pattern matching result variants

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"

Mapping and unwrapping results

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)

Requirements

  • OpenJDK 21 (or more)

Maven or Gradle setup:

  • 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>

About

Implementation of Result pattern for modern Java inspired by Rust std result crate. Perfectly suited for pattern matching.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages