Interface Try<Value>

Type Parameters:
Value - the type of the successful value
All Known Implementing Classes:
Try.Failure, Try.Success

@NullMarked public sealed interface Try<Value> permits Try.Success<Value>, Try.Failure<Value>
A monadic type that represents a computation that may either result in a value (Try.Success) or throw an exception (Try.Failure).

This interface is NullMarked: all methods return non-null values by default. The sole exception is getOrNull(), which may return null for two distinct reasons:

  1. This instance is a Try.Failure — no value is present.
  2. This instance is a Try.Success whose value is null, as produced by Try.run(...) which yields Success(null) on a successful void side-effect.

Success(null) is a valid and intentional state. Callers that need to distinguish "succeeded with null" from "failed" should use isSuccess(), fold(), or get() rather than getOrNull().

  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Interface
    Description
    static final record 
    Represents a computational failure within a context that implements the Try interface.
    static final record 
    Represents a successful computation result within the Try monad pattern.
  • Method Summary

    Modifier and Type
    Method
    Description
    static <V> Try<V>
    Creates a Try instance representing a failure with the given cause.
    default Try<Value>
    filter(Predicate<? super Value> predicate)
    Filters the Try based on the given predicate.
    default Try<Value>
    filter(Predicate<? super Value> predicate, Function<? super Value, ? extends Throwable> errorFn)
    Filters this Try using a predicate and a contextual error function that receives the value that failed the test.
    default Try<Value>
    filter(Predicate<? super Value> predicate, Supplier<? extends Throwable> throwableSupplier)
    Filters the Try based on the given predicate.
    default <NewValue> Try<NewValue>
    flatMap(Function<? super Value, Try<NewValue>> mapper)
    Applies the provided mapping function to the value contained within this `Try` instance if it represents a successful outcome.
    default Try<Value>
    flatMapError(Function<? super Throwable, ? extends Try<? extends Value>> mapper)
    Applies the given mapping function to the cause of a failed Try instance and returns the resulting Try.
    default <Folded> Folded
    fold(Function<? super Value, ? extends Folded> onSuccess, Function<? super Throwable, ? extends Folded> onFailure)
    Folds the current Try instance into a single value by applying one of two provided functions.
    static <V> Try<V>
    fromFuture(CompletableFuture<? extends V> future)
    Converts a CompletableFuture into a Try by blocking until the future completes.
    static <V> Try<V>
    fromOption(Option<? extends V> opt, Supplier<? extends Throwable> exceptionSupplier)
    Converts an Option to a Try.
    static <V> Try<V>
    fromOptional(Optional<? extends V> optional, Supplier<? extends Throwable> exceptionSupplier)
    Converts a Optional into a Try.
    static <V> Try<V>
    fromResult(Result<V, ? extends Throwable> result)
    Converts a Result into a Try instance.
    default Value
    get()
    Retrieves the value encapsulated in this instance if it represents a success.
    default Throwable
    Retrieves the cause of failure if the instance represents a failed state.
    default Value
    getOrElse(Value fallback)
    Returns the value if this instance is a Success, or the specified fallback value if it is a Failure.
    default Value
    getOrElseGet(Supplier<? extends Value> fallbackSupplier)
    Returns the value of this Try if it is a Success, or retrieves a fallback value using the provided fallbackSupplier if it is a Failure.
    default @Nullable Value
    Returns the value of this Try if it is a Success, or null if it is a Failure.
    default Value
    Returns the successful value if this instance is a Success, or throws an exception if this instance is a Failure.
    default Value
    getOrThrow(Function<? super Throwable, ? extends RuntimeException> exceptionMapper)
    Returns the value if this instance is a Success, or throws the exception provided by the exceptionMapper if this instance is a Failure.
    default boolean
    Determines if the current instance represents a failure state.
    default boolean
    Determines if the current instance represents a successful state.
    default <NewValue> Try<NewValue>
    map(Function<? super Value, ? extends NewValue> mapper)
    Transforms the value held by this instance using the provided mapping function.
    default Try<Value>
    mapFailure(Function<? super Throwable, ? extends Throwable> mapper)
    Transforms the failure cause using the given function, leaving a Success unchanged.
    static <V> Try<V>
    of(CheckedSupplier<? extends V> supplier)
    Creates a Try instance by executing the given CheckedSupplier.
    default Try<Value>
    onFailure(Consumer<? super Throwable> action)
    Executes a specified action if this instance represents a failure.
    default Try<Value>
    onSuccess(Consumer<? super Value> action)
    Performs the given action if the current instance represents a successful outcome.
    default <X extends Throwable>
    Try<Value>
    recover(Class<X> exceptionType, Function<? super X, ? extends Value> recovery)
    Recovers from a failure if — and only if — the exception is an instance of exceptionType, applying the recovery function to produce a new success value.
    default Try<Value>
    recover(Function<? super Throwable, ? extends Value> recoverFn)
    Recovers from a failure by applying a recovery function to the underlying throwable.
    default <X extends Throwable>
    Try<Value>
    recoverWith(Class<X> exceptionType, Function<? super X, ? extends Try<? extends Value>> recovery)
    Recovers from a failure if — and only if — the exception is an instance of exceptionType, by applying the recovery function which returns a new Try<Value> for chaining further fallible computations.
    default Try<Value>
    recoverWith(Function<? super Throwable, Try<Value>> recoverFn)
    Recovers from a failure by applying the given recovery function to the cause of the failure.
    static Try<Void>
    run(CheckedRunnable runnable)
    Executes the provided CheckedRunnable and returns a Try instance representing the outcome of the execution.
    static <V> Try<List<V>>
    sequence(Iterable<Try<V>> tries)
    Transforms an iterable of Try<V> into a single Try<List<V>>.
    static <V> Try<List<V>>
    sequence(Stream<Try<V>> tries)
    Transforms a stream of Try<V> into a single Try<List<V>>.
    default Stream<Value>
    Returns a single-element Stream containing the success value, or an empty stream on failure.
    static <V> Try<V>
    success(V value)
    Creates a successful Try instance containing the provided value.
    Converts this Try to an Either.
    Converts this Try into an already-completed CompletableFuture.
    default Option<Value>
    Converts the current instance to an Option.
    Converts the current Try instance into a Result representation.
    default <E> Result<Value,E>
    toResult(Function<? super Throwable, ? extends E> errorMapper)
    Converts this Try into a Result<Value, E> using a custom error mapper.
    static <A,B> Try<List<B>>
    traverse(Iterable<A> values, Function<? super A, Try<B>> mapper)
    Maps each element of an iterable through mapper and collects the results into a Try<List<B>>.
    static <A,B> Try<List<B>>
    traverse(Stream<A> values, Function<? super A, Try<B>> mapper)
    Maps each element of a stream through mapper and collects the results into a Try<List<B>>.
    static <V> Try<V>
    withTimeout(Duration timeout, CheckedSupplier<? extends V> supplier)
    Executes supplier on a virtual thread and returns the result as a Try.
    static <V1,V2> Try<Tuple2<V1,V2>>
    zip(Try<? extends V1> t1, Try<? extends V2> t2)
    Combines two Try values into a single Try containing a Tuple2.
    static <V1,V2,V3> Try<Tuple3<V1,V2,V3>>
    zip3(Try<? extends V1> t1, Try<? extends V2> t2, Try<? extends V3> t3)
    Combines three Try values into a single Try containing a Tuple3.
    static <V1,V2,V3,V4>
    Try<Tuple4<V1,V2,V3,V4>>
    zip4(Try<? extends V1> t1, Try<? extends V2> t2, Try<? extends V3> t3, Try<? extends V4> t4)
    Combines four Try values into a single Try containing a Tuple4.
    static <V1,V2,V3,R>
    Try<R>
    zipWith3(Try<? extends V1> t1, Try<? extends V2> t2, Try<? extends V3> t3, TriFunction<? super V1, ? super V2, ? super V3, ? extends R> combiner)
    Combines three Try values using a TriFunction.
    static <V1,V2,V3,V4,R>
    Try<R>
    zipWith4(Try<? extends V1> t1, Try<? extends V2> t2, Try<? extends V3> t3, Try<? extends V4> t4, QuadFunction<? super V1, ? super V2, ? super V3, ? super V4, ? extends R> combiner)
    Combines four Try values using a QuadFunction.
  • Method Details

    • success

      static <V> Try<V> success(V value)
      Creates a successful Try instance containing the provided value.
      Type Parameters:
      V - the type of the value contained in the Try instance
      Parameters:
      value - the value to be wrapped in a successful Try instance
      Returns:
      a Try instance representing a successful computation containing the given value
    • failure

      static <V> Try<V> failure(Throwable cause)
      Creates a Try instance representing a failure with the given cause.
      Type Parameters:
      V - the type of the value that would have been returned in case of success
      Parameters:
      cause - the throwable that caused the failure; must not be null
      Returns:
      a Try instance representing the failure
    • of

      static <V> Try<V> of(CheckedSupplier<? extends V> supplier)
      Creates a Try instance by executing the given CheckedSupplier. If the supplier executes successfully, a Try containing the result is returned. If an exception is thrown during execution, a Try containing the throwable is returned.
      Type Parameters:
      V - the type of the result supplied by the CheckedSupplier
      Parameters:
      supplier - the CheckedSupplier to execute
      Returns:
      a Try instance representing either a success with the supplied value or a failure with the thrown exception
    • run

      static Try<Void> run(CheckedRunnable runnable)
      Executes the provided CheckedRunnable and returns a Try instance representing the outcome of the execution.

      Note on null value: On success the returned Try<Void> wraps null as its value (since Void has no instances). This means that converting the result via toOption() will always return Option.none() — use isSuccess() or fold() instead to observe the outcome of a run() call.

      Parameters:
      runnable - the CheckedRunnable to be executed
      Returns:
      a Try<Void> representing the success or failure of the execution. On success, its value is null; on failure, it contains the thrown exception.
    • withTimeout

      static <V> Try<V> withTimeout(Duration timeout, CheckedSupplier<? extends V> supplier)
      Executes supplier on a virtual thread and returns the result as a Try. If the operation does not complete within timeout, the virtual thread is interrupted and a Failure containing a TimeoutException is returned.

      The TimeoutException message includes the configured duration in nanoseconds, e.g. "Operation timed out after 500000000ns". Nanosecond precision is used so that sub-millisecond timeouts are honoured without truncation.

      Requires Java 21+ (virtual threads).

      Example:

      Try<Response> result = Try.withTimeout(
          Duration.ofSeconds(5),
          () -> httpClient.get(url)
      );
      
      Type Parameters:
      V - the type of the result supplied
      Parameters:
      timeout - the maximum time to wait; must not be null
      supplier - the computation to run; must not be null
      Returns:
      Success(value) if the computation completes within the timeout, Failure(TimeoutException) if the timeout is exceeded, or Failure(cause) if the computation itself throws before the timeout
      Throws:
      NullPointerException - if timeout or supplier is null
    • isSuccess

      default boolean isSuccess()
      Determines if the current instance represents a successful state.
      Returns:
      true if the current instance is of type Success, false otherwise
    • isFailure

      default boolean isFailure()
      Determines if the current instance represents a failure state.
      Returns:
      true if the current instance is of type Failure, otherwise false.
    • get

      default Value get()
      Retrieves the value encapsulated in this instance if it represents a success. Throws a NoSuchElementException if this instance represents a failure.
      Returns:
      the value of this instance if it is a success
      Throws:
      NoSuchElementException - if this instance is a failure
    • getCause

      default Throwable getCause()
      Retrieves the cause of failure if the instance represents a failed state. For a successful state, this method throws a NoSuchElementException.
      Returns:
      the throwable cause of the failure if the instance is a Failure
      Throws:
      NoSuchElementException - if the instance is a Success as there is no cause
    • map

      default <NewValue> Try<NewValue> map(Function<? super Value, ? extends NewValue> mapper)
      Transforms the value held by this instance using the provided mapping function. If this instance represents a successful result, the mapping function is applied to its value. If this instance represents a failure, the failure is propagated.
      Type Parameters:
      NewValue - the type of the resulting value after applying the mapping function
      Parameters:
      mapper - the function to apply to the value if this instance represents a success
      Returns:
      a new instance of Try containing the mapped value if successful, or the original failure if unsuccessful
    • flatMap

      default <NewValue> Try<NewValue> flatMap(Function<? super Value, Try<NewValue>> mapper)
      Applies the provided mapping function to the value contained within this `Try` instance if it represents a successful outcome. The mapping function may produce a new `Try` instance representing either success or failure. If this instance is already a failure, it will return a failure with the same cause.
      Type Parameters:
      NewValue - the type of the result contained in the new `Try` instance
      Parameters:
      mapper - the mapping function to apply to the value, which produces a `Try` instance
      Returns:
      a new `Try` instance produced by applying the mapping function to the value, or a failure if either this instance is a failure or the function throws an exception
    • flatMapError

      default Try<Value> flatMapError(Function<? super Throwable, ? extends Try<? extends Value>> mapper)
      Applies the given mapping function to the cause of a failed Try instance and returns the resulting Try. If the instance represents success, the value is propagated unchanged.

      This is the dual of flatMap(Function): it operates on the failure channel instead of the value channel, allowing recovery from a known failure by running another fallible computation. If the mapper itself throws or returns null, the exception is captured and returned as a new Failure.

      Parameters:
      mapper - a function that maps the current cause to a new Try; must not be null
      Returns:
      the mapped Try for Failure, or this instance unchanged for Success
      Throws:
      NullPointerException - if mapper itself is null
    • onSuccess

      default Try<Value> onSuccess(Consumer<? super Value> action)
      Performs the given action if the current instance represents a successful outcome.
      Parameters:
      action - a Consumer to be executed with the value of a successful outcome
      Returns:
      the current Try instance
    • onFailure

      default Try<Value> onFailure(Consumer<? super Throwable> action)
      Executes a specified action if this instance represents a failure.
      Parameters:
      action - the action to be executed, accepting the throwable cause of the failure
      Returns:
      the current instance of Try<Value>
    • recover

      default Try<Value> recover(Function<? super Throwable, ? extends Value> recoverFn)
      Recovers from a failure by applying a recovery function to the underlying throwable. If the current instance represents a success, it is returned as is. Otherwise, the recovery function is applied to the cause of the failure to produce a new success value. If the recovery function itself throws an exception, the method returns a new failure wrapping the thrown exception.
      Parameters:
      recoverFn - the recovery function to apply in case of failure, accepting the throwable cause of the failure and producing a new value
      Returns:
      a Try instance representing either the original success, a new success generated by applying the recovery function, or a new failure resulting from an exception thrown by the recovery function
    • recoverWith

      default Try<Value> recoverWith(Function<? super Throwable, Try<Value>> recoverFn)
      Recovers from a failure by applying the given recovery function to the cause of the failure.
      Parameters:
      recoverFn - the function that takes a throwable and returns a new Try instance for recovery. It is applied only in case of a failure.
      Returns:
      the original success instance if this is a success, or the result of the recovery function if this is a failure.
    • recover

      default <X extends Throwable> Try<Value> recover(Class<X> exceptionType, Function<? super X, ? extends Value> recovery)
      Recovers from a failure if — and only if — the exception is an instance of exceptionType, applying the recovery function to produce a new success value.

      If this is a Success, or if the exception does not match exceptionType, this instance is returned unchanged. If the recovery function throws, the exception is captured as a new Failure.

      Type Parameters:
      X - the exception type to match
      Parameters:
      exceptionType - the class of the exception to recover from
      recovery - function that maps the matched exception to a recovery value
      Returns:
      a Success with the recovered value, or this instance if the exception did not match or if this is already a Success
    • recoverWith

      default <X extends Throwable> Try<Value> recoverWith(Class<X> exceptionType, Function<? super X, ? extends Try<? extends Value>> recovery)
      Recovers from a failure if — and only if — the exception is an instance of exceptionType, by applying the recovery function which returns a new Try<Value> for chaining further fallible computations.

      If this is a Success, or if the exception does not match exceptionType, this instance is returned unchanged. If the recovery function throws or returns null, the exception is captured as a new Failure.

      Type Parameters:
      X - the exception type to match
      Parameters:
      exceptionType - the class of the exception to recover from
      recovery - function that maps the matched exception to a new Try
      Returns:
      the result of the recovery function, or this instance if the exception did not match or if this is already a Success
    • getOrElse

      default Value getOrElse(Value fallback)
      Returns the value if this instance is a Success, or the specified fallback value if it is a Failure.
      Parameters:
      fallback - the value to return if this instance is a Failure.
      Returns:
      the value of this instance if it is a Success, or the specified fallback value if it is a Failure.
    • getOrElseGet

      default Value getOrElseGet(Supplier<? extends Value> fallbackSupplier)
      Returns the value of this Try if it is a Success, or retrieves a fallback value using the provided fallbackSupplier if it is a Failure.
      Parameters:
      fallbackSupplier - a Supplier that provides an alternative value to return if this Try is a Failure.
      Returns:
      the value of this Try if it is a Success, or the value supplied by fallbackSupplier if it is a Failure.
    • getOrNull

      default @Nullable Value getOrNull()
      Returns the value of this Try if it is a Success, or null if it is a Failure.
      Returns:
      the successful value if this Try is a Success, or null if it is a Failure.
    • getOrThrow

      default Value getOrThrow() throws Exception
      Returns the successful value if this instance is a Success, or throws an exception if this instance is a Failure.
      Returns:
      the successful value of this Try if it is a Success.
      Throws:
      Exception - if this Try is a Failure and the failure cause is an Exception.
      RuntimeException - if this Try is a Failure and the failure cause is not an Exception.
    • getOrThrow

      default Value getOrThrow(Function<? super Throwable, ? extends RuntimeException> exceptionMapper)
      Returns the value if this instance is a Success, or throws the exception provided by the exceptionMapper if this instance is a Failure.
      Parameters:
      exceptionMapper - a function to map the failure cause (Throwable) to a RuntimeException that will be thrown.
      Returns:
      the value if this is a Success.
      Throws:
      RuntimeException - if this is a Failure and the exceptionMapper is invoked.
    • fold

      default <Folded> Folded fold(Function<? super Value, ? extends Folded> onSuccess, Function<? super Throwable, ? extends Folded> onFailure)
      Folds the current Try instance into a single value by applying one of two provided functions. If this Try is a Success, the onSuccess function is applied to the value. If this Try is a Failure, the onFailure function is applied to the cause.
      Type Parameters:
      Folded - the type of the result after applying one of the functions
      Parameters:
      onSuccess - a function to apply to the value if this Try is a Success
      onFailure - a function to apply to the cause if this Try is a Failure
      Returns:
      the result of applying the appropriate function based on the state of this Try
    • filter

      default Try<Value> filter(Predicate<? super Value> predicate)
      Filters the Try based on the given predicate. If this is a Success and the predicate evaluates to true, the result is this Try instance. If the predicate evaluates to false, a Failure is returned using an IllegalArgumentException. If this is already a Failure, the result remains unchanged.

      On the Success path, if predicate is null or throws, a Failure(NullPointerException) or Failure(exception) is returned rather than propagating the error. An existing Failure is returned unchanged without evaluating the predicate, consistent with the Try philosophy of capturing throwables as values. See also filter(Predicate, Supplier) and filter(Predicate, java.util.function.Function).

      Parameters:
      predicate - the condition to evaluate for the value if this is a Success
      Returns:
      a Success if the predicate evaluates to true, or a Failure otherwise
    • filter

      default Try<Value> filter(Predicate<? super Value> predicate, Supplier<? extends Throwable> throwableSupplier)
      Filters the Try based on the given predicate. If this is a Success and the predicate evaluates to true, the result is this Try instance. If the predicate evaluates to false, a Failure is returned using the provided throwable supplier. If this is already a Failure, the result remains unchanged.

      On the Success path, if predicate or throwableSupplier is null, or if either throws, a Failure wrapping the throwable is returned rather than propagating the error. throwableSupplier is only invoked when the predicate evaluates to false. An existing Failure is returned unchanged without evaluating the predicate or the supplier, consistent with the Try philosophy of capturing throwables as values. See also filter(Predicate) and filter(Predicate, java.util.function.Function).

      Parameters:
      predicate - the condition to evaluate for the value if this is a Success
      throwableSupplier - a supplier to provide the throwable for the Failure if the predicate evaluates to false
      Returns:
      a Success if the predicate evaluates to true, or a Failure otherwise
    • filter

      default Try<Value> filter(Predicate<? super Value> predicate, Function<? super Value, ? extends Throwable> errorFn)
      Filters this Try using a predicate and a contextual error function that receives the value that failed the test. If this is a Failure, it is returned unchanged. If this is a Success and the predicate returns false, a Failure is returned with the throwable produced by errorFn applied to the value.

      Unlike filter(Predicate, Supplier), the error function can produce a message that includes the offending value:

      Try.of(() -> parseAge(input))
         .filter(age -> age >= 0, age -> new IllegalArgumentException("negative age: " + age));
      

      On the Success path, if predicate throws, the exception is captured and returned as a Failure; if errorFn returns null, a Failure(NullPointerException) is returned rather than propagating the NPE. errorFn is only invoked when the predicate evaluates to false. Note that a null predicate or errorFn is detected eagerly and does throw NullPointerException before any value is tested, regardless of whether this instance is a Success or Failure. See also filter(Predicate) and filter(Predicate, Supplier).

      Parameters:
      predicate - the condition to test the value; must not be null
      errorFn - a function that produces the throwable when the predicate fails; must not be null; if it returns null, a Failure(NullPointerException) is returned
      Returns:
      this instance if the predicate holds or this is already a Failure; otherwise a new Failure produced by errorFn
      Throws:
      NullPointerException - if predicate or errorFn is null
    • toResult

      default Result<Value, Throwable> toResult()
      Converts the current Try instance into a Result representation. If this Try is a Success, the resulting Result will be "ok" with the successful value. If this Try is a Failure, the resulting Result will be "err" with the failure cause.
      Returns:
      a Result instance where the success value is mapped to "ok" and the failure cause is mapped to "err".
    • toResult

      default <E> Result<Value,E> toResult(Function<? super Throwable, ? extends E> errorMapper)
      Converts this Try into a Result<Value, E> using a custom error mapper. If this is a Success, returns Ok with the same value. If this is a Failure, applies errorMapper to the cause and returns Err.

      This overload is preferred over toResult() when a typed error is needed:

      Result<Config, String> r = Try.of(this::loadConfig)
          .toResult(e -> "load failed: " + e.getMessage());
      
      Type Parameters:
      E - the error type of the resulting Result
      Parameters:
      errorMapper - a function that maps the failure cause to the error value; must not return null
      Returns:
      Ok(value) on success, or Err(errorMapper.apply(cause)) on failure
      Throws:
      NullPointerException - if errorMapper is null or returns null
    • fromResult

      static <V> Try<V> fromResult(Result<V, ? extends Throwable> result)
      Converts a Result into a Try instance. If the Result is successful (contains a value), a successful Try is returned. If the Result contains an error, a failed Try is returned with the corresponding cause.
      Type Parameters:
      V - the type of the successful value
      Parameters:
      result - the Result to convert into a Try
      Returns:
      a Try representing either the successful value or the failure cause contained in the Result
    • mapFailure

      default Try<Value> mapFailure(Function<? super Throwable, ? extends Throwable> mapper)
      Transforms the failure cause using the given function, leaving a Success unchanged. If this is a Failure and mapper itself throws, the thrown exception becomes the new cause (mirroring the behaviour of map(Function) on the success channel).

      Useful for wrapping low-level exceptions into domain exceptions:

      Try.of(db::query)
         .mapFailure(e -> new RepositoryException("query failed", e));
      
      Parameters:
      mapper - a function that maps the current cause to a new Throwable; must not return null
      Returns:
      this instance if Success, or a new Failure with the mapped cause; if mapper returns null or throws, the exception is wrapped as a new Failure
      Throws:
      NullPointerException - if mapper itself is null
    • stream

      default Stream<Value> stream()
      Returns a single-element Stream containing the success value, or an empty stream on failure. Mirrors Option.stream() for consistency.
      • Success(v) → Stream.of(v)
      • Failure → Stream.empty()
      Returns:
      a stream containing the value if this is a Success, or an empty stream otherwise
    • toOption

      default Option<Value> toOption()
      Converts the current instance to an Option. If the instance is a Success, wraps its value in an Option. If the instance is a Failure, returns an empty Option.
      Returns:
      an Option containing the value if the instance is a Success, or an empty Option if the instance is a Failure.
    • toEither

      default Either<Throwable, Value> toEither()
      Converts this Try to an Either.

      Success(v) maps to Either.right(Object); Failure(t) maps to Either.left(Object). This reflects the natural equivalence between Try<V> and Either<Throwable, V>.

      Note: unlike toOption(), this method does not tolerate a null success value, because Either enforces non-null values on both tracks. If this Try is a Success wrapping null (e.g. a Try<Void>), a NullPointerException will be thrown.

      Returns:
      an Either<Throwable, Value> equivalent of this Try
      Throws:
      NullPointerException - if this is a Success whose value is null
    • toFuture

      default CompletableFuture<Value> toFuture()
      Converts this Try into an already-completed CompletableFuture.

      If this is a Success, returns a future completed normally with the value. If this is a Failure, returns a future completed exceptionally with the cause.

      Returns:
      a completed CompletableFuture<Value>
    • fromOption

      static <V> Try<V> fromOption(Option<? extends V> opt, Supplier<? extends Throwable> exceptionSupplier)
      Converts an Option to a Try. If the Option contains a value, a successful Try is returned with that value. Otherwise, a failed Try is created using the supplied exception.
      Type Parameters:
      V - the type of the value contained in the Option.
      Parameters:
      opt - the Option to be converted into a Try, must not be null.
      exceptionSupplier - the supplier of the exception to be used when the Option is empty, must not be null.
      Returns:
      a Try representing either a success containing the value of the Option, or a failure containing the exception provided by the supplier.
    • fromOptional

      static <V> Try<V> fromOptional(Optional<? extends V> optional, Supplier<? extends Throwable> exceptionSupplier)
      Converts a Optional into a Try. If the Optional contains a value, returns Success with that value. If the Optional is empty, returns Failure with the exception provided by exceptionSupplier.
      Type Parameters:
      V - the value type
      Parameters:
      optional - the Optional to convert; must not be null
      exceptionSupplier - a supplier for the throwable to use when the Optional is empty; must not be null and must not return null
      Returns:
      Success(value) if the Optional is present, or Failure(exception) if empty
      Throws:
      NullPointerException - if optional or exceptionSupplier is null
    • fromFuture

      static <V> Try<V> fromFuture(CompletableFuture<? extends V> future)
      Converts a CompletableFuture into a Try by blocking until the future completes.

      If the future completes normally, returns Success(value). If the future completes exceptionally, the CompletionException wrapper is unwrapped and the original cause is stored as Failure(cause). If the future was cancelled, returns Failure(CancellationException).

      Type Parameters:
      V - the type of the future's value
      Parameters:
      future - the CompletableFuture to convert; must not be null
      Returns:
      Success(value) on normal completion, or Failure(cause) otherwise
      Throws:
      NullPointerException - if future is null
    • sequence

      static <V> Try<List<V>> sequence(Iterable<Try<V>> tries)
      Transforms an iterable of Try<V> into a single Try<List<V>>. If any element is a Failure, that failure is returned immediately (fail-fast). If all elements are Success, returns Success containing an unmodifiable list of values in encounter order.
      Type Parameters:
      V - the value type
      Parameters:
      tries - the iterable of Try values; must not be null and must not contain null elements
      Returns:
      Success(List<V>) if all elements succeed, or the first Failure encountered
      Throws:
      NullPointerException - if tries is null or contains a null element
    • sequence

      static <V> Try<List<V>> sequence(Stream<Try<V>> tries)
      Transforms a stream of Try<V> into a single Try<List<V>>. If any element is a Failure, that failure is returned immediately (fail-fast) and the stream is closed. If all elements are Success, returns Success containing an unmodifiable list of values in encounter order.
      Type Parameters:
      V - the value type
      Parameters:
      tries - the stream of Try values; must not be null and must not contain null elements
      Returns:
      Success(List<V>) if all elements succeed, or the first Failure encountered
      Throws:
      NullPointerException - if tries is null or contains a null element
    • traverse

      static <A,B> Try<List<B>> traverse(Iterable<A> values, Function<? super A, Try<B>> mapper)
      Maps each element of an iterable through mapper and collects the results into a Try<List<B>>. Fails fast on the first Failure returned by the mapper.
      Type Parameters:
      A - the input element type
      B - the mapped value type
      Parameters:
      values - the iterable of input values; must not be null
      mapper - a function that maps each value to a Try; must not be null and must not return null
      Returns:
      Success(List<B>) if all mappings succeed, or the first Failure produced by the mapper
      Throws:
      NullPointerException - if values or mapper is null, or if the mapper returns null
    • traverse

      static <A,B> Try<List<B>> traverse(Stream<A> values, Function<? super A, Try<B>> mapper)
      Maps each element of a stream through mapper and collects the results into a Try<List<B>>. Fails fast on the first Failure returned by the mapper; the stream is closed in all cases.
      Type Parameters:
      A - the input element type
      B - the mapped value type
      Parameters:
      values - the stream of input values; must not be null
      mapper - a function that maps each value to a Try; must not be null and must not return null
      Returns:
      Success(List<B>) if all mappings succeed, or the first Failure produced by the mapper
      Throws:
      NullPointerException - if values or mapper is null, or if the mapper returns null
    • zip

      static <V1,V2> Try<Tuple2<V1,V2>> zip(Try<? extends V1> t1, Try<? extends V2> t2)
      Combines two Try values into a single Try containing a Tuple2. Fail-fast: returns the first Failure encountered.
      Type Parameters:
      V1 - value type of the first try
      V2 - value type of the second try
      Parameters:
      t1 - first try; must not be null
      t2 - second try; must not be null
      Returns:
      Success(Tuple2(v1, v2)) if both succeed, otherwise the first Failure
      Throws:
      NullPointerException - if t1 or t2 is null
    • zip3

      static <V1,V2,V3> Try<Tuple3<V1,V2,V3>> zip3(Try<? extends V1> t1, Try<? extends V2> t2, Try<? extends V3> t3)
      Combines three Try values into a single Try containing a Tuple3. Fail-fast: returns the first Failure encountered.
      Type Parameters:
      V1 - value type of the first try
      V2 - value type of the second try
      V3 - value type of the third try
      Parameters:
      t1 - first try; must not be null
      t2 - second try; must not be null
      t3 - third try; must not be null
      Returns:
      Success(Tuple3(v1, v2, v3)) if all three succeed, otherwise the first Failure
      Throws:
      NullPointerException - if any argument is null
    • zipWith3

      static <V1,V2,V3,R> Try<R> zipWith3(Try<? extends V1> t1, Try<? extends V2> t2, Try<? extends V3> t3, TriFunction<? super V1, ? super V2, ? super V3, ? extends R> combiner)
      Combines three Try values using a TriFunction. Fail-fast: returns the first Failure encountered.
      Type Parameters:
      V1 - value type of the first try
      V2 - value type of the second try
      V3 - value type of the third try
      R - result value type
      Parameters:
      t1 - first try; must not be null
      t2 - second try; must not be null
      t3 - third try; must not be null
      combiner - function applied to the three values; must not be null
      Returns:
      Success(combiner(v1, v2, v3)) if all succeed, otherwise the first Failure
      Throws:
      NullPointerException - if any argument is null
    • zip4

      static <V1,V2,V3,V4> Try<Tuple4<V1,V2,V3,V4>> zip4(Try<? extends V1> t1, Try<? extends V2> t2, Try<? extends V3> t3, Try<? extends V4> t4)
      Combines four Try values into a single Try containing a Tuple4. Fail-fast: returns the first Failure encountered.
      Type Parameters:
      V1 - value type of the first try
      V2 - value type of the second try
      V3 - value type of the third try
      V4 - value type of the fourth try
      Parameters:
      t1 - first try; must not be null
      t2 - second try; must not be null
      t3 - third try; must not be null
      t4 - fourth try; must not be null
      Returns:
      Success(Tuple4(v1,v2,v3,v4)) if all four succeed, otherwise the first Failure
      Throws:
      NullPointerException - if any argument is null
    • zipWith4

      static <V1,V2,V3,V4,R> Try<R> zipWith4(Try<? extends V1> t1, Try<? extends V2> t2, Try<? extends V3> t3, Try<? extends V4> t4, QuadFunction<? super V1, ? super V2, ? super V3, ? super V4, ? extends R> combiner)
      Combines four Try values using a QuadFunction. Fail-fast: returns the first Failure encountered. If the combiner throws, the exception is captured as a Failure.
      Type Parameters:
      V1 - value type of the first try
      V2 - value type of the second try
      V3 - value type of the third try
      V4 - value type of the fourth try
      R - result value type
      Parameters:
      t1 - first try; must not be null
      t2 - second try; must not be null
      t3 - third try; must not be null
      t4 - fourth try; must not be null
      combiner - function applied to the four values; must not be null
      Returns:
      Success(combiner(v1,v2,v3,v4)) if all succeed, otherwise the first Failure
      Throws:
      NullPointerException - if any argument is null