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(); } } } 
1
  • 1
    Callable might be more suitable for "a Supplier that might throw an Exception" Commented Dec 25, 2020 at 8:30

2 Answers 2

1

Why not just:

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

?

Sign up to request clarification or add additional context in comments.

Comments

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; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.