0

I'm using vavr, and find there is no such util in Option, is there a similar handy util in any other package in java8?

public final class Utils {
    public static <T> Option<T> optionOfThrowableSupplier(Supplier<T> supplier){
        try {
            T x = supplier.get();
            return Option.some(x);
        } catch (Exception e) {
            return Option.none();
        }
    }
}
luochen1990
  • 3,689
  • 1
  • 22
  • 37

2 Answers2

1

Why not just:

Try.of(() -> "throwable supplier").toOption()

?

Opal
  • 81,889
  • 28
  • 189
  • 210
0

It doesn't seems such utility exist. I suggest to create a Supplier wrapper class to solve this problem, which convert the given Supplier<T> to Supplier<Option<T>> and the get method will return Option.none(); when exception is thrown.

import java.util.function.Supplier;

import io.vavr.control.Option;

public class HandleExceptionOptionSupplier<T> implements Supplier<Option<T>> {
    public static void main(String[] args) {
        Supplier<String> noErrorSupplier = () -> {
            return "Success";
        };
        Supplier<String> errorSupplier = () -> {
            throw new RuntimeException("");
        };
        System.out.println(new HandleExceptionOptionSupplier<String>(noErrorSupplier).get()
                .getOrElse("No element"));
        System.out.println(new HandleExceptionOptionSupplier<String>(errorSupplier).get()
                .getOrElse("No element"));
    }

    private final Supplier<T> throwableSupplier;

    /**
     * return {@link Option#some(Object)} when the throwableSupplier has no error,
     * when there is exception, return {@link Option#none()}
     */
    @Override
    public Option<T> get() {
        try {
            T value = throwableSupplier.get();
            return Option.some(value);
        } catch (Exception e) {
            return Option.none();
        }
    }

    /**
     * @param throwableSupplier the supplier to wrap
     */
    public HandleExceptionOptionSupplier(Supplier<T> throwableSupplier) {
        this.throwableSupplier = throwableSupplier;
    }
}
samabcde
  • 6,988
  • 2
  • 25
  • 41