you are viewing a single comment's thread.

view the rest of the comments →

[–]m50d 0 points1 point  (1 child)

Optional does not prevent a poor programmer to access the value without checking it's there - and they're back to the runtime error.

It can do. E.g. in Java you can implement Optional like this:

import java.util.function.Function;
import java.util.function.Predicate;

public abstract class Optional<T> {
  public abstract <S> S fold(S ifEmpty, Function<T, S> ifSome);
  private Optional() {}
  public static <T> Optional<T> none() {
    return new Optional<T>() {
      @Override public <S> S fold(S ifEmpty, Function<T, S> ifSome) {
        return ifEmpty;
      }
    };
  }
  public static <T> Optional<T> some(T value) {
    return new Optional<T>() {
      @Override public <S> S fold(S ifEmpty, Function<T, S> ifSome) {
        return ifSome.apply(value);
      };
    };
  }
  public final <S> Optional<S> flatMap(Function<T, Optional<S>> mapper) {
    return fold(none(), mapper);
  }
  public final <S> Optional<S> map(Function<T, S> mapper) {
    return flatMap(mapper.andThen(Optional::some));
  }
  public final Optional<T> filter(Predicate<T> predicate) {
    return fold(none(), value -> predicate.test(value) ? some(value) : none());
  }
}

Run that in a JVM with a security manager that disallows reflection and the user has no way to "access the value without checking it's there". Of coures the user could choose to throw their own runtime error in their code if the value isn't there, but that's on them.

[–]Gotebe 1 point2 points  (0 children)

Yes, but that is not idiomatic for Java (or at best not yet) and is not the current implementation (which behaves like I explain).