1

In my opinion, Java 8 and later versions (actually 9 and 10) lack of a piece to efficiently use Stream and other monads. Java does not have any kind of Try monad to handle errors during monad composition.

Why? Initially, I thought that was a lack of only the version 8, but I do not find any JEP to introduce it in the JDK.

Something like the following could be a starting point.

public class Try<T> {
    private T value;
    private Exception exception;

    private Try(Supplier<T> supplier) {
        try {
            this.value = supplier.get();
        } catch (Exception ) {
            this.exception = ex;
        }
    }

    Optional<T> toOptional() {
        return Optional.ofNullable(value);
    }

    public static <T> Try<T> of(Supplier<T> supplier) {
        return new Try<>(supplier);
    }
    // Some other interesting methods...
}

Maybe not anyone uses reactive streams, but during a stream transformation, you need some smart way to collect exceptions, without breaking the whole stream execution.

stream
   .map(info -> {
        // Code that can rise an exception
        // Without the Try monad is tedious to handle exceptions!
   })
   .filter(/* something */)
   .to(/* somewhere */)

Can anyone explain me why? Is it related to some other specification lack?

Thanks to all.

riccardo.cardin
  • 7,971
  • 5
  • 57
  • 106

0 Answers0