1 package io.atlassian.fugue;
2
3 /**
4 * Helpers to work with functions that may throw exceptions. Used with
5 * {@link Try}.
6 *
7 * @since 4.4.0
8 */
9 public class Checked {
10 // do not ctor
11 private Checked() {}
12
13 /**
14 * Represents a {@link Function} that may throw an exception.
15 *
16 * @param <A> the type of the input to the function
17 * @param <B> the type of the result of the function
18 * @param <E> The type of exception potentially thrown
19 */
20 @FunctionalInterface public interface Function<A, B, E extends Exception> {
21 B apply(A t) throws E;
22
23 default public java.util.function.Function<A, Try<B>> lift() {
24 return Checked.lift(this);
25 }
26 }
27
28 /**
29 * Represents a {@link Supplier} that may throw an exception.
30 *
31 * @param <A> the type of the result of the supplier
32 * @param <E> The type of exception potentially thrown
33 */
34 @FunctionalInterface public interface Supplier<A, E extends Exception> {
35 A get() throws E;
36
37 default public Try<A> attempt() {
38 return of(this);
39 }
40 }
41
42 /**
43 * Lifts a function that potentially throws into a function that either
44 * returns a Success of the value or a failure containing the thrown
45 * exception.
46 *
47 * @param f a function that can throw
48 * @param <A> the function argument type
49 * @param <B> the function return type
50 * @param <E> The type of exception potentially thrown
51 * @return the argument function lifted into returning a Try
52 *
53 */
54 public static <A, B, E extends Exception> java.util.function.Function<A, Try<B>> lift(Checked.Function<A, B, E> f) {
55 return a -> Checked.of(() -> f.apply(a));
56 }
57
58 /**
59 * Create a new Try representing the result of a potentially exception
60 * throwing operation. If the provided supplier throws an exception this will
61 * return a failure wrapping the exception, otherwise a success of the
62 * supplied value will be returned.
63 *
64 * @param s a supplier that may throw an exception
65 * @param <A> the type of value s supplies
66 * @param <E> The type of exception potentially thrown
67 * @return If s throws an exception this will return a failure wrapping the
68 * exception, otherwise a success of the supplied value.
69 */
70 public static <A, E extends Exception> Try<A> of(Checked.Supplier<A, E> s) {
71 try {
72 return Try.successful(s.get());
73 } catch (final Exception e) {
74 return Try.failure(e);
75 }
76 }
77 }