Class Ok<T,E>

java.lang.Object
dev.kylesilver.result.Ok<T,E>
Type Parameters:
T - The type of the value wrapped by this class.
E - The type of an Err that could have (but in this case did not) resulted from the parent operation.
All Implemented Interfaces:
Result<T,E>

public class Ok<T,E> extends Object implements Result<T,E>
Indicates that an operation has been completed successfully.
  • Constructor Details

    • Ok

      public Ok(@NotNull T t)
  • Method Details

    • isOk

      public boolean isOk()
      Description copied from interface: Result
      Indicates whether the wrapped value is an Ok.
      Specified by:
      isOk in interface Result<T,E>
      Returns:
      true if the wrapper is Ok, otherwise false.
    • isErr

      public boolean isErr()
      Description copied from interface: Result
      Indicates whether the wrapped value is an Err.
      Specified by:
      isErr in interface Result<T,E>
      Returns:
      true if the wrapper is Err, otherwise false.
    • ok

      public Optional<T> ok()
      Description copied from interface: Result
      Get the Ok value if it exists.
      Specified by:
      ok in interface Result<T,E>
      Returns:
      the underlying value if the result is Ok, otherwise the value will be empty.
      See Also:
    • err

      public Optional<E> err()
      Description copied from interface: Result
      Get the Err value if it exists.
      Specified by:
      err in interface Result<T,E>
      Returns:
      the underlying value if the result is an Err, otherwise the value will be empty.
      See Also:
    • unwrap

      public T unwrap()
      Description copied from interface: Result
      Retrieve the Ok value or throw an exception if the result is an Err.
      Specified by:
      unwrap in interface Result<T,E>
      Returns:
      the value of Ok without an Optional wrapper.
    • unwrapErr

      public E unwrapErr() throws UnwrapException
      Description copied from interface: Result
      Retrieve the Err value or throw an UnwrapException if the result is Ok. If the error is a Throwable, it will not be thrown. To throw a custom error, use Result.expect(Function).
      Specified by:
      unwrapErr in interface Result<T,E>
      Returns:
      the value of Err without an Optional wrapper.
      Throws:
      UnwrapException - if the result is not Err.
    • expect

      public T expect(String errorMessage)
      Description copied from interface: Result
      Return the value if Ok, otherwise throw an exception with a custom error message.
      Specified by:
      expect in interface Result<T,E>
      Parameters:
      errorMessage - The message to accompany the UnwrapException if thrown.
      Returns:
      The value, if Ok.
    • expect

      public <F extends Throwable> T expect(Function<E,F> mapping)
      Description copied from interface: Result
      Returns the value or throws a caller-defined exception.
      Specified by:
      expect in interface Result<T,E>
      Type Parameters:
      F - Type of the thrown exception.
      Parameters:
      mapping - Lambda for creating the thrown exception.
      Returns:
      The value, if Ok.
    • expectErr

      public E expectErr(String errorMessage) throws UnwrapException
      Description copied from interface: Result
      Return the value if Err, otherwise throw an exception with a custom error message.
      Specified by:
      expectErr in interface Result<T,E>
      Parameters:
      errorMessage - The message to accompany the UnwrapException if thrown.
      Returns:
      The value, if Err.
      Throws:
      UnwrapException - If the result is Ok.
    • expectErr

      public <F extends Throwable> E expectErr(Function<T,F> mapping) throws F
      Description copied from interface: Result
      Returns the value or throws a caller-defined exception.
      Specified by:
      expectErr in interface Result<T,E>
      Type Parameters:
      F - Type of the thrown exception.
      Parameters:
      mapping - Lambda for creating the thrown exception.
      Returns:
      The value, if Err.
      Throws:
      F - Thrown if the result is Ok.
    • match

      public <U> U match(Function<T,U> ifOk, Function<E,U> ifErr)
      Description copied from interface: Result
      Apply a transformation to the value of a result.

      In the example below, the parseArgs function attempts to convert a user-provided string to a list of integers, but failing that returns its input unmodified. The output of the function is then used to determine the number of valid user-provided arguments and do some additional logging for convenience.

      
       Result<List<Integer>, String> parsed = parseArgs(input);
       int validArgs = parsed.match(
           ok -> ok.size(),
           err -> {
               log.warn("The provided input could not be parsed: \"{}\"", err);
               return 0;
           }
       );
       
      Note that unlike Result.map(Function), both the Ok and Err values must be mapped to a single output type.
      Specified by:
      match in interface Result<T,E>
      Type Parameters:
      U - the type of the value to be returned after the transformations are applied. Both transformations must converge to this type.
      Parameters:
      ifOk - the transformation that is applied to the underlying data if the result is Ok.
      ifErr - the transformation that is applied to the underlying data if the result is an Err.
      Returns:
      a value of type U after applying one of the two provided transformations.
    • match

      public void match(Consumer<T> ifOk, Consumer<E> ifErr)
      Description copied from interface: Result
      Apply a lambda with no return type to the value of a result.

      This is useful for things which produce side effects such as logging. In contrast to Result.match(Function, Function), no output can be obtained from an invocation of this method. In the example below, some informational logging is performed on the parseArgs function.

      
       Result<List<Integer>, String> parsed = parseArgs(input);
       parsed.match(
           ok -> log.info("args were parsed successfully: {}", ok),
           err -> log.warn("The provided input could not be parsed: \"{}\"", err)
       );
       
      Specified by:
      match in interface Result<T,E>
      Parameters:
      ifOk - the lambda that is applied to the underlying data if the result is Ok.
      ifErr - the lambda that is applied to the underlying data if the result is an Err.
    • map

      public <U> Result<U,E> map(Function<T,U> mapping)
      Description copied from interface: Result
      Apply a transformation to the wrapped value if the result is Ok. If the result is an Err, no transformation will be applied.
      
       assertEquals(
           6,
           Result.ok(5).map(x -> x + 1).unwrap()
       );
       assertEquals(
           "error",
           Result.<Integer, String>err("error").map(x -> x + 1).unwrapErr()
       );
       
      If an exception is thrown while applying mapping, the exception will not be caught. Ensure that any lambda passed to this function does not throw any runtime exceptions.
      Specified by:
      map in interface Result<T,E>
      Type Parameters:
      U - the type of the output of the transformation.
      Parameters:
      mapping - the transformation to apply to the wrapped value if the result is Ok.
      Returns:
      a new Result containing either the transformed value or the original error.
    • mapErr

      public <F> Result<T,F> mapErr(Function<E,F> mapping)
      Description copied from interface: Result
      Apply a transformation to the wrapped value if the result is an Err. If the result is Ok, no transformation will be applied.
      
       assertEquals(
           "error: 'foo'",
            Result.err("foo").mapErr(err -> String.format("error: '%s'", err)).unwrapErr()
       );
       assertEquals(
           5,
           Result.ok(5).mapErr(err -> String.format("error: '%s'", err)).unwrap()
       );
       
      If an exception is thrown while applying mapping, the exception will not be caught. Ensure that any lambda passed to this function does not throw any runtime exceptions.
      Specified by:
      mapErr in interface Result<T,E>
      Type Parameters:
      F - the type of the output of the transformation.
      Parameters:
      mapping - the transformation to apply to the wrapped value if the result is an Err.
      Returns:
      a new Result containing either the transformed error or the original value.
    • and

      public <U> Result<U,E> and(Result<U,E> result)
      Description copied from interface: Result
      Returns the provided argument if the result is Ok and propagates the original Err otherwise.
      
       assertEquals(
           Result.err("first error"),
           Result.err("first error").and(Result.err("second error"))
       );
       assertEquals(
           Result.err("second error"),
           Result.ok(1).and(Result.err("second error"))
       );
       assertEquals(
           Result.ok(2),
           Result.ok("success").and(Result.ok(2))
       );
       
      Specified by:
      and in interface Result<T,E>
      Type Parameters:
      U - the type of the Ok value in the new result.
      Parameters:
      result - the value to be returned if the result is Ok.
      Returns:
      either the original error or the caller-provided Result.
    • andThen

      public <U> Result<U,E> andThen(Function<T,Result<U,E>> resultFn)
      Description copied from interface: Result
      Apply a fallible operation to the wrapped value if the result is Ok. If the result is an Err, the error is propagated to the next operation in the chain.

      This operation differs from map in that if the value yielded by the provided fallible operation is an error, it is returned without being wrapped in a redundant, enclosing Result. Take, for example, two functions: getUserInput() which returns a Result<String, RuntimeException> and parseInt(String s) which returns a Result<Integer, NumberFormatException>. A chain of operations could be built up as follows:

      
       Result<Integer, RuntimeException> result = getUserInput().andThen(parseInt);
       
      If map had been used instead, the chain would have looked like:
      
       Result<Result<Integer, NumberFormatException>, NoSuchElementException> result = getUserInput().map(parseInt);
       
      Specified by:
      andThen in interface Result<T,E>
      Type Parameters:
      U - the output type of resultFn.
      Parameters:
      resultFn - the function to be applied if the result is Ok.
      Returns:
      either the output of resultFn or the original error.
    • or

      public <F> Result<T,F> or(Result<T,F> result)
      Description copied from interface: Result
      Returns the provided argument if the result is an Err and propagates the original Ok value otherwise.
      
       assertEquals(
           Result.ok("success"),
           Result.err("error").or(Result.ok("success"))
       );
       assertEquals(
           Result.ok("first"),
           Result.ok("first").or(Result.ok("second"))
       );
       assertEquals(
           Result.err("second"),
           Result.err("first").or(Result.err("second"))
       );
       
      Specified by:
      or in interface Result<T,E>
      Type Parameters:
      F - the type of the Err value in the new result.
      Parameters:
      result - the value to be returned if the result is an Err.
      Returns:
      either the original value or the caller-provided Result.
    • orElse

      public <F> Result<T,F> orElse(Function<E,Result<T,F>> resultFn)
      Description copied from interface: Result
      Apply a fallible operation to the wrapped value if the result is an Err. If the result is Ok, the value is propagated to the next operation in the chain.
      
       assertEquals(
           Result.ok("recovered from err: foo"),
           Result.err("foo").orElse(err -> Result.ok("recovered from err: " + err))
       );
       assertEquals(
           Result.ok("no error"),
           Result.ok("no error").orElse(err -> Result.ok("recovered from err: " + err))
       );
       
      Specified by:
      orElse in interface Result<T,E>
      Type Parameters:
      F - the type of the Err value in the new result.
      Parameters:
      resultFn - the function to be applied if the result is an Err.
      Returns:
      either the output of resultFn or the original value.