Interface Try<T>

  • Type Parameters:
    T - The type of the value represented by this Try
    All Superinterfaces:
    java.lang.Iterable<T>
    All Known Implementing Classes:
    Failure, Success

    public interface Try<T>
    extends java.lang.Iterable<T>
    The Try type represents a computation that may either result in an exception, or return a successfully computed value.
    Typical use case is situations where parallel computation takes place resulting in more than one response where it's possible that one or more computations fail.
    Though it might not be desirable to raise an exception for failed computations hence the Try acts a place holder for a response that is either failed or successful.
    Instances of Try, are either an instance of Success or Failure.
    Example of usage:
     Try<SomeData> getSomeData(SomeInput input) {
         try {
             // readUserFromDB throws if no user exists
             SomeData data = readUserFromDB(input);
             return new Success<>(data);
         } catch (SomeException ex) {
             return new Failure<>(ex);
         }
     }
     
    A more elaborate way is to provide a checked function provided to the apply(ThrowableFunction0) method.
     Try<Integer> resultSuccess = Try.apply(() -> 9 / 3); // results in Success(3)
     Try<Integer> resultFailure = Try.apply(() -> 9 / 0); // results in Failure(ArithmeticException)
     
    Or let us re-write the first example to use the apply(ThrowableFunction0) method.
     Try<SomeData> getSomeData(SomeInput input) {
         // readUserFromDB throws if no user exists
         Try.apply(() -> readUserFromDB(input));
     }
     
    To make it even more concise we can create Try instances just by using Try(ThrowableFunction0).
    This however requires you to statically import the proper methods from the companion class related to Try.
     import static javascalautils.TryCompanion.Try;
    
     Try<SomeData> getSomeData(SomeInput input) {
         // readUserFromDB throws if no user exists
         Try(() -> readUserFromDB(input));
     }
     
    Since:
    1.0
    • Method Detail

      • apply

        static <T> Try<T> apply​(T value)
        Creates an instance of Try.
        If a null or non-throwable value is provided then Success is returned containing the value, else Failure containing the provided throwable.
        Type Parameters:
        T - The type for the Try
        Parameters:
        value - The value for this to create a Try
        Returns:
        The Try instance
        Since:
        1.0
      • apply

        static <T> Try<T> apply​(ThrowableFunction0<T> function)
        Creates an instance of Try wrapping the result of the provided function.
        If the function results in a value then Success with the value is returned.
        In case the function raises an exception then Failure is returned containing that exception.
        If null is provided as argument then the apply(Object) is invoked.
        Example simple division by zero results in an exception.
         Try<Integer> resultSuccess = Try.apply(() -> 9 / 3); // results in Success(3)
         Try<Integer> resultFailure = Try.apply(() -> 9 / 0); // results in Failure(ArithmeticException)
         
        Type Parameters:
        T - The type for the Try
        Parameters:
        function - The function to render either the value T or raise an exception.
        Returns:
        The resulting Try instance wrapping what the function resulted in
        Since:
        1.3
      • isFailure

        default boolean isFailure()
        Returns true if the Try is a Failure, false otherwise.
        Returns:
        If the Try is a Failure
        Since:
        1.0
      • isSuccess

        boolean isSuccess()
        Returns true if the Try is a Success, false otherwise.
        Returns:
        If the Try is a Success
        Since:
        1.0
      • getOrElse

        T getOrElse​(java.util.function.Supplier<T> supplier)
        Returns the value from this Success or the value provided by the supplier if this is a Failure.
        Parameters:
        supplier - The supplier to return the value in case of a Failure
        Returns:
        The value from the Try or the supplier
        Since:
        1.0
      • orNull

        default T orNull()
        Returns the value if it is a Success, else null.
        Returns:
        The value of the Try or null.
        Since:
        1.0
      • orElse

        Try<T> orElse​(java.util.function.Supplier<Try<T>> supplier)
        Returns this Try if it's a Success or the value provided by the supplier if this is a Failure.
        Parameters:
        supplier - The supplier to return the value in case of a Failure
        Returns:
        This try or the value from the supplier
      • get

        T get()
        throws java.lang.Throwable
        Returns the value from this Success or throws the exception if this is a Failure.
        Returns:
        The value of the Success
        Throws:
        java.lang.Throwable - The Throwable in case of a Failure
        Since:
        1.0
      • failed

        Try<java.lang.Throwable> failed()
        Completes this Try with an exception wrapped in a Success.
        The exception is either the exception that the Try failed with (if a Failure) or an 'UnsupportedOperationException'.
        Returns:
        The value of the Failure in a Success
        Since:
        1.0
      • filter

        Try<T> filter​(java.util.function.Predicate<T> filter)
        Applies the predicate to the value of the Try and either returns the Try if the predicate matched or a Failure.
        One of the three outcomes are applicable:
        • Instance is Success and predicate matches -> return this
        • Instance is Success and predicate does not match -> return Failure
        • Instance is Failure -> return this
        Parameters:
        filter - The filter to apply
        Returns:
        The try matching the filter, either this if matching or a Failure in case no match
        Since:
        1.4
      • iterator

        java.util.Iterator<T> iterator()
        Returns the Try's value in an Iterator if it is a Success, or an empty Iterator if it is Failure.
        Specified by:
        iterator in interface java.lang.Iterable<T>
        Returns:
        The iterator for the Try
        Since:
        1.0
      • map

        <R> Try<R> map​(ThrowableFunction1<T,​R> function)
        Maps the given function to the value from this Success or returns this if this is a Failure.
        This allows for mapping a Try containing some type to some completely different type.
        The example converts a Try of type String to Integer.
         Try<String> t = ...
         Try<Integer> t2 = t.map(v -> v.length);
         
        Type Parameters:
        R - The type for the return value from the function
        Parameters:
        function - The function to use
        Returns:
        The Option containing the mapped value
        Since:
        1.0
      • flatMap

        <R> Try<R> flatMap​(ThrowableFunction1<T,​Try<R>> function)
        Maps the given function to the value from this Success or returns this if this is a Failure.
        Type Parameters:
        R - The type for the return value from the function
        Parameters:
        function - The function to use
        Returns:
        The Option containing the mapped value
        Since:
        1.2
      • recover

        Try<T> recover​(ThrowableFunction1<java.lang.Throwable,​T> function)
        Creates a new Try that in case this Try is a Failure will apply the function to recover to a Success.
        Should this be a Success then this is returned, i.e. no new instance is created.
        This is a kind of map(ThrowableFunction1) for failures only.
        E.g.
        In case of t being successful then that value is passed on to recovered, in case of failure then the recover function kicks in and returns the message from the throwable.
         Try<String> t = ...
         Try<String> recovered = t.recover(t -> t.getMessage());
        
         
        This statement will be Success(3)
        Try<Integer> t = Try(() -> 9/3).recover(t -> 0)

        Whilst this statement will be Success(0) as it is division-by-zero
        Try<Integer> t = Try(() -> 9/0).recover(t -> 0)
        Parameters:
        function - The function to apply in case of a Failure
        Returns:
        The recovered Try
        Since:
        1.4
      • recoverWith

        Try<T> recoverWith​(ThrowableFunction1<java.lang.Throwable,​Try<T>> function)
        Creates a new Try that in case this Try is a Failure will apply the function to recover the Try rendered by the function.
        Should this be a Success the value is propagated as-is.
        This is a kind of map(ThrowableFunction1) for failures only.
        E.g.
         Try<String> t = ...
         Try<String> recovered = t.recover(t -> new Success<>(t.getMessage()));
         
        In case of t being successful then that value is passed on to recovered, in case of failure then the recover function kicks in and returns the a Success with message from the throwable.
        Parameters:
        function - The function to apply in case of a Failure
        Returns:
        The recovered Try
        Since:
        1.4
      • stream

        java.util.stream.Stream<T> stream()
        Returns the Try's value in a Stream if it is a Success, or an empty Stream if it is a Failure.
        Returns:
        The stream for the Try
        Since:
        1.0
      • asOption

        default Option<T> asOption()
        Returns this Try as an Option.
        If it is a Success then the value is wrapped in Some else None is returned.
        Should the Success contain a null value the result will be None as null values are per definition none/nothing.
        Returns:
        The Option representing this Try
        Since:
        1.0