Skip to content

About

Result<T, E> for Java

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Result<T, E> for Java

A type-safe Result library for Java, inspired by Rust's Result<T, E>. Instead of throwing exceptions, methods return explicit success or failure values — making error handling visible, composable, and impossible to accidentally ignore.

Features

  • Pattern matching — use switch expressions directly over result types
  • Sealed interfaces and records — no class hierarchies; everything is a closed, known type
  • Fluent chaining — convert and transform across all three result types
  • Serializable by default — as long as your generic types are serializable
  • 100% test coverage — quite easy without branching
  • List and combination support — stream over lists of results or combine them into a single result.

The three result types

Type States Use when
Result<T, E> Ok(T) or Err(E) An operation that either succeeds with a value or fails
OptionalResult<T, E> Present(T), Empty, or OptErr(E) An operation that may succeed with a value, succeed with nothing, or fail
VoidResult<E> VoidOk or VoidErr(E) An operation that either succeeds (with no value) or fails

Quick start

Import into a gradle project using:

implementation 'dev.mhh:result:1.1.0'

Instead of throwing an exception, return a Result:

Result<String, String> parseInput(String input) {
    var trimmed = input.trim();
    if (trimmed.isBlank()) return Result.err("Input is required");
    return Result.ok(trimmed);
}

Callers decide how to handle the result — with a switch expression, fluent chain, or any combination:

// Pattern match: handle each case explicitly
Json restEndpoint(String input) {
    return switch (parseInput(input)) {
        case Ok(var value) -> buildSuccess(value);
        case Err(var err)  -> buildError(err);
    };
}

// Or throw in contexts where the error is truly unexpected
void internalMethod(String input) {
    switch (parseInput(input)) {
        case Ok(var value) -> process(value);
        case Err(var err)  -> throw new IllegalStateException("Unexpected error: " + err);
    }
}

Fluent chaining

Results can be transformed and converted across types in a single chain, without intermediate variables or defensive checks at each step:

VoidResult<String> result = Result.ok(rawInput)
    .map(String::trim)
    .mapToOptional(s -> Optional.of(s).filter(Predicate.not(String::isBlank)))
    .toResult(() -> "Input must not be blank")
    .verify(InputVerifier::verify)
    .toVoidResult();

If any step produces an error, the rest of the chain short-circuits — the error is carried through unchanged.


Collecting streams of results

ResultCollector is a standard Collector that partitions a stream of Result values into either a list of all successes or a list of all errors. The stream is always consumed in full before the final result is determined.

Result<List<Integer>, List<String>> result = Stream.of(
        Result.ok(1),
        Result.err("oops"),
        Result.ok(3)
    )
    .collect(ResultCollector.collector());

If every element is Ok, the returned result is Ok containing a list of all unwrapped values. If any element is Err, the returned result is Err containing a list of all unwrapped errors. Encounter order is preserved in both cases.