Class Result<T,​E>

  • Type Parameters:
    T - the type of the success value
    E - the type of the error value

    public class Result<T,​E>
    extends Object
    A container object representing either a successful result or an error.

    Inspired by Rust's Result<T, E> and Scala's Either[L, R], this class provides a functional approach to error handling without exceptions. It forces explicit handling of both success and failure cases, leading to more robust code.

    Creating Results

    
     // Success case
     Result<User, ApiError> success = Result.success(new User("John"));
    
     // Failure case
     Result<User, ApiError> failure = Result.failure(new ApiError(404, "Not found"));
     

    Checking and Extracting Values

    
     Result<User, ApiError> result = client.fluent().get("/users/1", User.class);
    
     if (result.isSuccess()) {
         User user = result.getValue();
         System.out.println("Found: " + user.getName());
     } else {
         ApiError error = result.getError();
         System.err.println("Error: " + error.getMessage());
     }
     

    Pattern Matching with match()

    
     result.match(
         user -> System.out.println("Success: " + user.getName()),
         error -> System.err.println("Failed: " + error.getMessage())
     );
     

    Functional Transformations

    
     // Transform the success value
     Result<String, ApiError> nameResult = result.map(user -> user.getName());
    
     // Transform the error
     Result<User, String> stringError = result.mapError(err -> err.getMessage());
    
     // Chain operations
     String name = result
         .map(User::getName)
         .map(String::toUpperCase)
         .getOrElse("Unknown");
     

    Safe Value Extraction

    
     // With default value
     User user = result.getOrElse(User.anonymous());
    
     // With lazy default
     User user = result.getOrElseGet(() -> loadDefaultUser());
    
     // Throw on failure
     User user = result.getOrElseThrow(() -> new UserNotFoundException());
    
     // Unwrap (throws RuntimeException on failure)
     User user = result.unwrap();
    
     // Convert to Optional
     Optional<User> optional = result.toOptional();
     
    Since:
    1.0.0
    Author:
    guinetik <guinetik@gmail.com>
    See Also:
    RocketRest.FluentApi, ApiError
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      static <T,​E>
      Result<T,​E>
      failure​(E error)
      Creates a failed Result containing the given error.
      E getError()
      Gets the error contained in this Result.
      T getOrElse​(T defaultValue)
      Gets the value contained in this Result or the given default value if this Result is a failure.
      T getOrElseGet​(Supplier<? extends T> supplier)
      Gets the value contained in this Result or the value supplied by the given Supplier if this Result is a failure.
      <X extends Throwable>
      T
      getOrElseThrow​(Supplier<? extends X> exceptionSupplier)
      Gets the value contained in this Result or throws the given exception if this Result is a failure.
      T getValue()
      Gets the value contained in this Result.
      Result<T,​E> ifFailure​(Consumer<? super E> consumer)
      Executes the given consumer if this Result is a failure.
      Result<T,​E> ifSuccess​(Consumer<? super T> consumer)
      Executes the given consumer if this Result is a success.
      boolean isFailure()
      Returns whether this Result is a failure.
      boolean isSuccess()
      Returns whether this Result is a success.
      <U> Result<U,​E> map​(Function<? super T,​? extends U> mapper)
      Maps the value of this Result if it's a success, using the given mapping function.
      <F> Result<T,​F> mapError​(Function<? super E,​? extends F> mapper)
      Maps the error of this Result if it's a failure, using the given mapping function.
      Result<T,​E> match​(Consumer<? super T> successConsumer, Consumer<? super E> errorConsumer)
      Pattern-matches over this Result, executing one of the consumers depending on success/failure.
      static <T,​E>
      Result<T,​E>
      success​(T value)
      Creates a successful Result containing the given value.
      Optional<T> toOptional()
      Converts this Result to an Optional containing the value if this Result is a success, or an empty Optional if this Result is a failure.
      String toString()  
      T unwrap()
      Returns the value if this Result is a success, or unwraps the error by throwing an exception.
    • Method Detail

      • success

        public static <T,​E> Result<T,​E> success​(T value)
        Creates a successful Result containing the given value.
        Type Parameters:
        T - the type of the value
        E - the type of the error
        Parameters:
        value - the value
        Returns:
        a successful Result containing the value
      • failure

        public static <T,​E> Result<T,​E> failure​(E error)
        Creates a failed Result containing the given error.
        Type Parameters:
        T - the type of the value
        E - the type of the error
        Parameters:
        error - the error
        Returns:
        a failed Result containing the error
      • isSuccess

        public boolean isSuccess()
        Returns whether this Result is a success.
        Returns:
        true if this Result is a success, false otherwise
      • isFailure

        public boolean isFailure()
        Returns whether this Result is a failure.
        Returns:
        true if this Result is a failure, false otherwise
      • getValue

        public T getValue()
        Gets the value contained in this Result.
        Returns:
        the value
        Throws:
        NoSuchElementException - if this Result is a failure
      • getError

        public E getError()
        Gets the error contained in this Result.
        Returns:
        the error
        Throws:
        NoSuchElementException - if this Result is a success
      • getOrElse

        public T getOrElse​(T defaultValue)
        Gets the value contained in this Result or the given default value if this Result is a failure.
        Parameters:
        defaultValue - the value to return if this Result is a failure
        Returns:
        the value if this Result is a success, otherwise the default value
      • getOrElseGet

        public T getOrElseGet​(Supplier<? extends T> supplier)
        Gets the value contained in this Result or the value supplied by the given Supplier if this Result is a failure.
        Parameters:
        supplier - the Supplier to provide the default value
        Returns:
        the value if this Result is a success, otherwise the value from the supplier
      • getOrElseThrow

        public <X extends ThrowableT getOrElseThrow​(Supplier<? extends X> exceptionSupplier)
                                               throws X extends Throwable
        Gets the value contained in this Result or throws the given exception if this Result is a failure.
        Type Parameters:
        X - the type of the exception to throw
        Parameters:
        exceptionSupplier - the Supplier to provide the exception to throw
        Returns:
        the value if this Result is a success
        Throws:
        X - if this Result is a failure
        X extends Throwable
      • unwrap

        public T unwrap()
        Returns the value if this Result is a success, or unwraps the error by throwing an exception. This is similar to Rust's unwrap() method.
        Returns:
        the contained value
        Throws:
        RuntimeException - if this is a failure, with the error toString() as the message
      • map

        public <U> Result<U,​E> map​(Function<? super T,​? extends U> mapper)
        Maps the value of this Result if it's a success, using the given mapping function.
        Type Parameters:
        U - the type of the result of the mapping function
        Parameters:
        mapper - the function to apply to the value
        Returns:
        a new Result with the mapped value if this Result is a success, otherwise a new Result with the same error
      • mapError

        public <F> Result<T,​F> mapError​(Function<? super E,​? extends F> mapper)
        Maps the error of this Result if it's a failure, using the given mapping function.
        Type Parameters:
        F - the type of the result of the mapping function
        Parameters:
        mapper - the function to apply to the error
        Returns:
        a new Result with the mapped error if this Result is a failure, otherwise a new Result with the same value
      • ifSuccess

        public Result<T,​E> ifSuccess​(Consumer<? super T> consumer)
        Executes the given consumer if this Result is a success.
        Parameters:
        consumer - the consumer to execute
        Returns:
        this Result
      • ifFailure

        public Result<T,​E> ifFailure​(Consumer<? super E> consumer)
        Executes the given consumer if this Result is a failure.
        Parameters:
        consumer - the consumer to execute
        Returns:
        this Result
      • toOptional

        public Optional<T> toOptional()
        Converts this Result to an Optional containing the value if this Result is a success, or an empty Optional if this Result is a failure.
        Returns:
        an Optional containing the value if this Result is a success, otherwise an empty Optional
      • match

        public Result<T,​E> match​(Consumer<? super T> successConsumer,
                                       Consumer<? super E> errorConsumer)
        Pattern-matches over this Result, executing one of the consumers depending on success/failure.
         result.match(value -> System.out.println(value), err -> log.error(err));
         
        Parameters:
        successConsumer - runs if this result is a success (receives the value)
        errorConsumer - runs if this result is a failure (receives the error)
        Returns:
        this Result for fluent chaining